#!/usr/bin/env python
# coding: utf-8

# <h1>Table of Contents<span class="tocSkip"></span></h1>
# <div class="toc"><ul class="toc-item"><li><span><a href="#Matplotlib-(Teil-2)" data-toc-modified-id="Matplotlib-(Teil-2)-1"><span class="toc-item-num">1&nbsp;&nbsp;</span>Matplotlib (Teil 2)</a></span><ul class="toc-item"><li><span><a href="#Wiederholung" data-toc-modified-id="Wiederholung-1.1"><span class="toc-item-num">1.1&nbsp;&nbsp;</span>Wiederholung</a></span></li><li><span><a href="#Achsen-und-Gitterlinien" data-toc-modified-id="Achsen-und-Gitterlinien-1.2"><span class="toc-item-num">1.2&nbsp;&nbsp;</span>Achsen und Gitterlinien</a></span></li><li><span><a href="#Reihenfolge-der-Elemente-festlegen" data-toc-modified-id="Reihenfolge-der-Elemente-festlegen-1.3"><span class="toc-item-num">1.3&nbsp;&nbsp;</span>Reihenfolge der Elemente festlegen</a></span></li><li><span><a href="#Bilder-abspeichern" data-toc-modified-id="Bilder-abspeichern-1.4"><span class="toc-item-num">1.4&nbsp;&nbsp;</span>Bilder abspeichern</a></span></li><li><span><a href="#Logarithmische-Skalierung" data-toc-modified-id="Logarithmische-Skalierung-1.5"><span class="toc-item-num">1.5&nbsp;&nbsp;</span>Logarithmische Skalierung</a></span></li><li><span><a href="#Vektorpfeile" data-toc-modified-id="Vektorpfeile-1.6"><span class="toc-item-num">1.6&nbsp;&nbsp;</span>Vektorpfeile</a></span></li><li><span><a href="#Flächen-füllen" data-toc-modified-id="Flächen-füllen-1.7"><span class="toc-item-num">1.7&nbsp;&nbsp;</span>Flächen füllen</a></span></li><li><span><a href="#Zeichnen-von-2d-reellwertigen-Daten-(imshow-und-contour)" data-toc-modified-id="Zeichnen-von-2d-reellwertigen-Daten-(imshow-und-contour)-1.8"><span class="toc-item-num">1.8&nbsp;&nbsp;</span>Zeichnen von 2d reellwertigen Daten (imshow und contour)</a></span></li></ul></li><li><span><a href="#3D-Plots" data-toc-modified-id="3D-Plots-2"><span class="toc-item-num">2&nbsp;&nbsp;</span>3D Plots</a></span><ul class="toc-item"><li><span><a href="#Polygonzug-in-3D" data-toc-modified-id="Polygonzug-in-3D-2.1"><span class="toc-item-num">2.1&nbsp;&nbsp;</span>Polygonzug in 3D</a></span></li><li><span><a href="#Fläche-in-3d-mit-plot_surface" data-toc-modified-id="Fläche-in-3d-mit-plot_surface-2.2"><span class="toc-item-num">2.2&nbsp;&nbsp;</span>Fläche in 3d mit <strong>plot_surface</strong></a></span></li><li><span><a href="#Vektorpfeile-in-3d-mit-quiver" data-toc-modified-id="Vektorpfeile-in-3d-mit-quiver-2.3"><span class="toc-item-num">2.3&nbsp;&nbsp;</span>Vektorpfeile in 3d mit <strong>quiver</strong></a></span></li></ul></li></ul></div>

# # Matplotlib (Teil 2)

# In[ ]:


import numpy as np
import matplotlib.pyplot as plt
#modus für Vorlesung
#plt.rcParams['figure.figsize'] = (9., 3.)
#plt.rcParams['lines.linewidth'] = 3
#%matplotlib qt5agg
#modus für Export nach pdf
get_ipython().run_line_magic('matplotlib', 'inline')
plt.rcParams["figure.figsize"] = (3.0, 2.0) #default figsize für Export nach pdf


# In[ ]:


import matplotlib
from matplotlib.backends import backend_registry
# interactive backends
#backend_registry.list_builtin(matplotlib.backends.BackendFilter.INTERACTIVE)

# noninteractive backends
backend_registry.list_builtin(matplotlib.backends.BackendFilter.NON_INTERACTIVE)

# all backends built into Matplotlib
# backend_registry.list_builtin()

# all registered backends
#backend_registry.list_all()


# In[ ]:


#plt.rcParams.keys()


# https://matplotlib.org/stable/gallery/color/named_colors.html

# ## Wiederholung

# In[ ]:


fig, ax = plt.subplots(1, 3, layout='constrained')
fig.suptitle('super titel')
fig.set_facecolor('azure')

ax[0].set_title('ax 1 title right', loc='right', color='purple', fontsize=8)
ax[0].set_facecolor('navy')


# In[ ]:


def f(t):
    return t**2 * np.exp(-t**2)


t = np.linspace(0, 3, 51)
y = f(t)

ax[0].plot(t, y, color='yellow', label='$t^2\\exp(-t^2)$')
ax[0].legend();


# ## Achsen und Gitterlinien 
# Hinzufügen von Achsenbezeichnungen.  __layout='constrained'__ in plt.subplots  sorgt dafür das alles sichtbar bleibt.

# In[ ]:


ax[0].set_xlabel('t', color='red', fontsize=24)
ax[0].set_ylabel('f(t)');


# In[ ]:


ax[1].set_facecolor('grey')
ax[1].grid(color='white')
ax[1].plot(y, t, color='gold', alpha=.5);


# In[ ]:


phi = np.linspace(0, 2 * np.pi)
ax[2].plot(np.cos(phi), np.sin(phi), 'm', zorder=1)
ax[2].scatter(np.cos(phi[::5]), np.sin(phi[::5]), s=20 + 10 * phi[::5])
ax[2].set_aspect('equal')
# Setze die bottom und left Achsen (engl. spines) als x und y Achse
ax[2].spines['bottom'].set_position('zero')
ax[2].spines['left'].set_position('zero')
# Entferne top und right spines
ax[2].spines['top'].set_visible(False)
ax[2].spines['right'].set_visible(False)


# In[ ]:


ax[2].set_xlim((-2, 2))
ax[2].set_ylim((-2, 2))
ax[2].set_xticks([-1, 0, 1])
ax[2].set_yticks([-1, 0, 1]);


# ## Reihenfolge der Elemente festlegen 
# _zorder_ legt fest in welcher Reihenfolge die Elemente gezeichnet werden.

# In[ ]:


x = np.linspace(0, 7)

plt.figure()
plt.plot(x, np.sin(x), label='zorder=1', color='blue', zorder=1)
plt.plot(x, np.sin(x + 1), label='zorder=3', color='orange', zorder=3)
plt.axhline(0, label='zorder=2', color='lightgrey', zorder=2)

plt.title('z order der Element')
l = plt.legend(loc='upper right')
l.set_zorder(2)
plt.show()


# Position der Legende 
# 
# | Location String |  Location Code |
# | :- | :-: |
# |'best'|  0 |
# 'upper right' |    1
# 'upper left'  |   2
# 'lower left'  |  3
# 'lower right' |  4
# 'right'       |  5
# 'center left' |  6
# 'center right'|  7
# 'lower center'|  8
# 'upper center'|  9
# 'center'      |  10

# ## Bilder abspeichern
# Bild in einer Datei (pdf, jpeg, ...) speichern:
# 
# __savefig__

# In[ ]:


fig.savefig('bild1.pdf')  # das format wird anhand der Endung geraten


# In[ ]:


fig.savefig('bild1.jpg', format='jpg')


# In[ ]:


#fig.canvas.get_supported_filetypes_grouped()


# ## Logarithmische Skalierung
# Verwendung logarithmischer Achsen:

# In[ ]:


x = np.linspace(1, 10, 21)
y = 2**(-x)
fig, ax = plt.subplots(1)
ax.semilogy(x, y, '+');


# Siehe auch <code>semilogx()</code> und <code>loglog()</code>, wenn die x-Achse bzw. beide Achsen logarithmisch skaliert werden sollen.

# ## Vektorpfeile
# Vektorpfeile mit
# 
# __quiver__

# In[ ]:


fig, ax = plt.subplots(figsize=(3, 3))
x, y, u, v = 0, 0, 1, .5

ax.quiver(x, y, u, v)  # (x,y) Fusspunkt (u,v) Richtung
ax.set_title('Quiver mit einem Pfeil')
ax.axis([-2, 2, -2, 2])
ax.grid()


# In[ ]:


fig, ax = plt.subplots(figsize=(3, 3))
x, y, u, v = 0, 0, 1, .5

ax.quiver(x, y, u, v, angles='xy', scale_units='xy', scale=1)
ax.set_title('Quiver mit einem Pfeil')
ax.axis([-2, 2, -2, 2])
ax.grid()
ax.set_aspect('equal')


# In[ ]:


fig, ax = plt.subplots(figsize=(3, 3))
n = 7
t = np.linspace(0, 2 * np.pi, n)[:-1]
x = np.cos(t)
y = np.sin(t)
u = np.sin(t)
v = -np.cos(t)
color = t
# Punkte an Koordinate (x_i, y_i) s: Größe  c: Farbe 
ax.scatter(x, y, s=5 * t + 5, c=color, cmap='plasma')

qv = ax.quiver(x, y, u, v, color, angles='xy', scale_units='xy',
               scale=1, cmap='plasma')
ax.set_title('Quiver mit vielen Pfeilen')
ax.axis([-2, 2, -2, 2])
ax.set_aspect('equal')

fig.colorbar(qv);


# Der Parameter __cmap__ wählt die Colormap aus.  
# Link zu Colormaps (cmap) https://matplotlib.org/stable/tutorials/colors/colormaps.html

# ## Flächen füllen
# 
# __fill__

# In[ ]:


fig, ax = plt.subplots(1)
ax.plot([0, 1, 0, 0], [0, 0, 1, 0])
ax.axis(xmin=-.01, ymin=-.01);


# In[ ]:


fig, ax = plt.subplots(1)
ax.fill([0, 1, 0, 0], [0, 0, 1, 0], color='red')
ax.axis(xmin=-.01, ymin=-.01);


# In[ ]:


x = np.linspace(0, 1.8 * np.pi)
y1 = np.sin(x)


# In[ ]:


fig, ax = plt.subplots(1)
ax.fill(x, y1)
ax.plot(x, y1, 'xr')
ax.axis('equal');


# ## Zeichnen von 2d reellwertigen Daten (imshow und contour)
# <code>imshow<code> zum darstellen von gepixelten Bildern

# In[ ]:


i = np.arange(5)
M = (-1)**(i[:, np.newaxis] + i)
fig, ax = plt.subplots(1)
ax.imshow(M, cmap='Greys')


# In[ ]:


plt.close('all')


# In[ ]:


from matplotlib.image import imread

img = imread('bild1.jpg')
img.shape


# In[ ]:


plt.figure()
plt.imshow(img)


# <code>contour</code> berechnet und zeichnet Höhenlinien auf einem  kartesichen Gitter
# 
# ```python
#     contour(x, y, z, levels)
# ```
# <code>x, y</code> : Arrays mit den Koordinaten für den Wert z
# 
# <code>levels</code> : Anzahl der Höhenlinine oder Werte für die Höhenlinien

# In[ ]:


fig, ax = plt.subplots(1)
x = np.linspace(-2, 2)
y = np.linspace(-2, 2)
xx, yy = np.meshgrid(x, y)
zz = xx**2 - yy**2
cs = ax.contour(xx, yy, zz, [-1, 1])
cs.clabel()
ax.axis('equal');


# # 3D Plots

# ## Polygonzug in 3D

# In[ ]:


# erzeugen ein 3D Koordinatensystem
ax = plt.figure().add_subplot(projection='3d')


# In[ ]:


x = np.random.rand(5)
y = np.random.rand(5)
z = np.random.randn(5)

ax.plot(x, y, z, 'co-');


# In[ ]:


fig = plt.figure(figsize=(4, 4))
ax = fig.add_subplot(projection='3d')

x, y = [-1, 1, 1, -1, -1], [-1, -1, 1, 1, -1] 
for z in (-1, 1):                       # Zwei Quadrate
    ax.plot(x, y, [z] * 5, color="r")
for a, b in zip(x[:4], y[:4]):          # verbinde die vier Ecken der Quadrate
    ax.plot([a, a], [b, b], [-1, 1], color="b")
    
ax.set_box_aspect((1, 1, 1))


# ## Fläche in 3d mit __plot_surface__

# In[ ]:


fig, ax = plt.subplots(1, 2, layout='constrained', subplot_kw={'projection': '3d'})

phi = np.linspace(0, 2 * np.pi, 12, endpoint=False).reshape(-1,1)
theta = np.linspace(0, np.pi, 12).reshape(1, -1)
theta = np.append(theta, np.nan) #nan Trick um ungewünschte Linien zu entfernen

# Parametrisierung der Kugelfläche siehe https://de.wikipedia.org/wiki/Kugel
x = np.cos(phi) * np.sin(theta)  # durch broadcasting sind x, y, z hier 2D arrays
y = np.sin(phi) * np.sin(theta)
z = np.ones_like(phi) * np.cos(theta)

ax[0].plot(x.flatten(), y.flatten(), z.flatten(), 'ro-', linewidth=1)
ax[1].plot_surface(x, y, z);


# ## Vektorpfeile in 3d mit __quiver__

# In[ ]:


fig = plt.figure(figsize=(5, 5))
ax = fig.add_subplot(projection='3d')

phi = np.linspace(0, 2 * np.pi, 6, endpoint=False).reshape(-1, 1)
theta = np.linspace(0, np.pi, 6, endpoint=False).reshape(1, -1)

# durch broadcasting sind u, v, w hier 2D arrays
u = np.cos(phi) * np.sin(theta)  
v = np.sin(phi) * np.sin(theta)
w = np.ones_like(phi) * np.cos(theta)

ax.quiver(0, 0, 0, u, v, w)
ax.set_box_aspect((1, 1, 1))


# In[ ]:


ax.set_xlim(-2, 2)
ax.set_ylim(-2, 2)
ax.set_zlim(-2, 2)


# In[ ]:


plt.close('all')


# In[ ]:


u


# In[ ]:




