# Beispiele in MatPlotLib¶

Links:

https://www.python-kurs.eu/matplotlib.php

https://towardsdatascience.com/matplotlib-tutorial-learn-basics-of-pythons-powerful-plotting-library-b5d1b8f67596

https://matplotlib.org/3.1.1/tutorials/index.html

Vorsicht: In Jupyter ist diese Zeile immer notwendig:

      %matplotlib inline

Für Markdown-Syntax siehe: https://sourceforge.net/p/jupiter/wiki/markdown_syntax/

## Array darstellen¶

In [2]:

    import matplotlib.pyplot as plt
    %matplotlib inline
    plt.plot([-1, -4.5, 16, 23, 15, 59])
    plt.show()

## X/Y Array¶

In [2]:

    import matplotlib.pyplot as plt
    %matplotlib inline
    plt.plot([1,2,3,4,5,6,7,8,9,10],[-5,-4,-3,-2,-1,0,1,2,3,4])
    plt.title("X/Y Array")
    plt.xlabel("x-werte")
    plt.ylabel("y-werte")
    plt.show()

## Mit Format-String / Farbcode¶

    '-'  (Bindestrich) durchgezogene Linie
    '--'  (zwei Bindestriche) gestrichelte Linie
    '-.' Strichpunkt-Linie
    ':' punktierte Linie
    '.' Punkt-Marker
    ',' Pixel-Marker
    'o' Kreis-Marker
    'v' Dreiecks-Marker, Spitze nach unten
    '^' Dreiecks-Marker, Spitze nach oben
    '<' Dreiecks-Marker, Spitze nach links
    '>' Dreiecks-Marker, Spitze nach rechs
    '1' tri-runter-Marker
    '2' tri-hoch-Marker
    '3' tri-links Marker
    '4' tri-rechts Marker
    's' quadratischer Marker
    'p' fünfeckiger Marker
    '*' Stern-Marker
    'h' Sechseck-Marker1
    'H' Sechseck-Marker2
    '+' Plus-Marker
    'x' x-Marker
    'D' rautenförmiger Marker
    'd' dünner rautenförmiger Marker
    '|' Marker in Form einer vertikalen Linie

    Zeichen    Farbe

    'b' blau
    'g' grün
    'r' rot
    'c' cyan
    'm' magenta
    'y' gelb
    'k' schwarz
    'w' weiß

## Mit berechneten Funktionswerten¶

In [4]:

    months = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
    revenue = [52, 74, 79, 95, 115, 110, 129, 126, 147, 146, 156, 184]
    b=2.355
    m=17.78333333333333
    y = [m*x + b for x in months]
    plt.plot(months, revenue, "o")
    plt.plot(months, y)
    plt.show()

In [3]:

    import matplotlib.pyplot as plt
    %matplotlib inline
    plt.plot([-1, -4.5, 16, 23, 15, 59],"",
             [-1, -4.5, 16, 23, 15, 59],"bD")
    plt.show()

## Achsen verändern¶

In [4]:

    import matplotlib.pyplot as plt
    %matplotlib inline
    plt.plot([-1, -4.5, 16, 23, 15, 59],"",
             [-1, -4.5, 16, 23, 15, 59],"bD")
    xmin, xmax, ymin, ymax = 0, 10, -10, 60
    plt.axis([xmin, xmax, ymin, ymax])
    plt.show()

## Linestyle für gleichverteilte x-Werte¶

In [5]:

    import numpy as np
    import matplotlib.pyplot as plt
    %matplotlib inline
    X = np.linspace(0, 2 * np.pi, 50, endpoint=True)
    F1 = 3 * np.sin(X)
    F2 = np.sin(2*X)
    F3 = 0.3 * np.sin(X)
    F4 = np.cos(X)
    plt.plot(X, F1, color="blue", linewidth=2.5, linestyle="-")
    plt.plot(X, F2, color="red", linewidth=1.5, linestyle="--")
    plt.plot(X, F3, color="green", linewidth=2, linestyle=":")
    plt.plot(X, F4, color="grey", linewidth=2, linestyle="-.")
    plt.show()

In [6]:

    x = np.linspace(0, 2, 100)

    plt.plot(x, x, label='linear')
    plt.plot(x, x**2, label='quadratic')
    plt.plot(x, x**3, label='cubic')

    plt.xlabel('x label')
    plt.ylabel('y label')

    plt.title("Simple Plot")

    plt.legend()

    plt.show()

## Koordinaten-Achsen¶

In [7]:

    import numpy as np
    import matplotlib.pyplot as plt
    %matplotlib inline
    X  = np.linspace(-2 * np.pi, 2 * np.pi, 70, endpoint=True)
    F1 = np.sin(2* X)
    # aktuellen Plot zuweisen:
    ax = plt.gca()
    # Obere und rechte Achse unsichtbar werden lassen:
    ax.spines['top'].set_color('none')
    ax.spines['right'].set_color('none')
    # Untere Achse auf die y=0 Position bewegen:
    ax.xaxis.set_ticks_position('bottom')
    ax.spines['bottom'].set_position(('data',0))
    # Linke Achse auf die Position x == 0 bewegen:
    ax.yaxis.set_ticks_position('left')
    ax.spines['left'].set_position(('data',0))
    plt.plot(X, F1)
    plt.show()

In [8]:

    import numpy as np
    import matplotlib.pyplot as plt
    %matplotlib inline
    X = np.linspace(-2 * np.pi, 2 * np.pi, 70, endpoint=True)
    F1 = np.sin(X**2)
    F2 = X * np.sin(X)
    # aktuelle Achsen werden zurückgeliefert,
    # falls notwendig, werden sie erzeugt:
    ax = plt.gca()
    # der obere rechte Spine wird unsichtbar gemacht:
    ax.spines['top'].set_color('none')
    ax.spines['right'].set_color('none')
    # der untere Spine wird in Position y=0  gebracht:
    ax.xaxis.set_ticks_position('bottom')
    ax.spines['bottom'].set_position(('data',0))
    # der linke Spine wird nach rechts zu x == 0 bewegt:
    ax.yaxis.set_ticks_position('left')
    ax.spines['left'].set_position(('data',0))
    plt.xticks( [-6.28, -3.14, 3.14, 6.28])
    plt.yticks([-3, -1, 0, +1, 3])
    plt.plot(X, F1)
    plt.plot(X, F2)
    plt.show()

In [9]:

    import numpy as np
    import matplotlib.pyplot as plt
    %matplotlib inline
    X = np.linspace(-2 * np.pi, 2 * np.pi, 70, endpoint=True)
    F1 = X * np.sin(X)
    ax = plt.gca()
    ax.spines['top'].set_color('none')
    ax.spines['right'].set_color('none')
    ax.xaxis.set_ticks_position('bottom')
    ax.spines['bottom'].set_position(('data',0))
    ax.yaxis.set_ticks_position('left')
    ax.spines['left'].set_position(('data',0))
    # Labelung der X-Achse:
    plt.xticks( [-6.28, -3.14, 3.14, 6.28],
            [r'$-2\pi$', r'$-\pi$', r'$+\pi$', r'$+2\pi$'])
    plt.yticks([-3, -1, 0, +1, 3])
    plt.plot(X, F1)
    plt.show()

## Legende¶

In [10]:

    import numpy as np
    import matplotlib.pyplot as plt
    %matplotlib inline
    X = np.linspace(-2 * np.pi, 2 * np.pi, 70, endpoint=True)
    F1 = np.sin(0.5*X)
    F2 = -3 * np.cos(0.8*X)
    plt.xticks( [-6.28, -3.14, 3.14, 6.28],
            [r'$-2\pi$', r'$-\pi$', r'$+\pi$', r'$+2\pi$'])
    plt.yticks([-3, -1, 0, +1, 3])
    plt.plot(X, F1, label="$sin(0.5x)$")
    plt.plot(X, F2, label="$-3 cos(0.8x)$")
    plt.legend(loc='best')
    plt.show()

## Gitterlinien und Grafik speichern¶

In [11]:

    import numpy as np
    import matplotlib.pyplot as plt
    %matplotlib inline
    def f(t):
        return np.exp(-t) * np.cos(2*np.pi*t)
    def g(t):
        return np.sin(t) * np.cos(1/(t+0.1))
    t1 = np.arange(0.0, 5.0, 0.1)
    t2 = np.arange(0.0, 5.0, 0.02)
    fig = plt.figure()
    plt.subplot(212)
    plt.plot(t1, g(t1), 'ro', t2, f(t2), 'k')
    plt.grid(color='b', alpha=0.5, linestyle='dashed', linewidth=0.5)
    plt.show()
    fig.savefig('filename.png', dpi=200)

## Scatter-Plot¶

In [12]:

    height = np.array([167,170,149,165,155,180,166,146,
    159,185,145,168,172,181,169])
    weight = np.array ([86,74,66,78,68,79,90,73,
    70,88,66,84,67,84,77])
    plt.xlim(140,200)
    plt.ylim(60,100)
    plt.scatter(height,weight)
    plt.title("Scatter Plot")
    plt.xlabel("Height")
    plt.ylabel("Weight")
    plt.show()

    from mpl_toolkits import mplot3d

    ax = plt.axes(projection='3d')
    ax.scatter3D(height,weight)
    ax.set_xlabel("Height")
    ax.set_ylabel("Weight")
    plt.show()

    ax = plt.axes(projection='3d')
    ax.plot3D(height,weight)
    plt.show()

## Diagramme¶

In [13]:

    plt.rcdefaults()
    fig, ax = plt.subplots()
    personen = ('Michael', 'Dorothea', 'Robert', 'Bea', 'Uli')
    y_pos = np.arange(len(personen))
    verbrauch = (15, 22, 24, 39, 12)
    ax.barh(y_pos, verbrauch, align='center',
            color='green', ecolor='black')
    ax.set_yticks(y_pos)
    ax.set_yticklabels(personen)
    ax.invert_yaxis()  # labels von oben nach unten
    ax.set_xlabel('Verbrauch')
    ax.set_title('Kaffeekonsum')
    plt.show()

    parteien = ["CDU/CSU", "SPD", "AfD", "FDP", "Linke", "Grüne", "Sonst."]
    colors = ['black', 'orangered', 'blue',  'yellow',  'red', 'green', 'grey']
    anteile = [32.9, 20.5, 12.6, 10.7, 9.2, 8.9, 5]
    bars = plt.bar(parteien, anteile, color=colors)
    plt.title("Ergebnisse Bundestagswahlkampf 2017")
    plt.show()

    firms=["Firm A", "Firm B", "Firm C", "Firm D","Firm E"]
    market_share = [20, 25, 15,10,20]
    Explode=[0,0.1,0,0,0]
    plt.pie(market_share,explode=Explode,labels=firms,shadow=True,startangle=45)
    plt.axis('equal')
    plt.legend(title="Lịst of Firms")
    plt.show()

### Unterdiagramme¶

In [1]:

    import numpy as np

    X = np.array([ [156.3,158.9,160.8,179.6,156.6,165.1,165.9,156.7,167.8,160.8],   # Körpergröße
                   [ 62  , 52  , 83  , 69  , 74  , 52  , 77  , 65  , 79  , 51  ],   # Gewicht
                   [ 24  , 34  , 26  , 51  , 43  , 33  , 22  , 21  , 19  , 34  ]    # Alter
                 ])
    y = np.array(  [ 48.1, 46.8, 49.3, 51.2, 48.7, 49.0, 50.6, 47.1, 51.7, 47.8])
    print(X)
    print(y)

    import matplotlib.pyplot as plt
    # Unterdiagramme siehe u.a. https://www.python-kurs.eu/matplotlib_unterdiagramme.php

    plt.figure(figsize=(20, 5))  # insgesamt 20 breit und 5 hoch

    """
    plt.subplot(131)             # 1 rows, 3 column, index 1 -> plt.subplot(1,3,1)
    plt.scatter(X[0], y,color='blue')
    plt.subplot(132)             # 1 rows, 3 column, index 2 -> plt.subplot(1,3,2)
    plt.scatter(X[1], y,color='red')
    plt.subplot(133)             # 1 rows, 3 column, index 3 -> plt.subplot(1,3,3)
    plt.scatter(X[2], y,color='green')
    """
    # alternative
    colors = ['blue','red','green']
    titles = ['Körpergröße','Gewicht','Alter']
    for i in range(3):
        plt.subplot(1,3,i+1)
        plt.scatter(X[i], y,color=colors[i])
        plt.title('Ringgröße in Abhängigkeit von '+ titles[i])

    plt.show()

    [[156.3 158.9 160.8 179.6 156.6 165.1 165.9 156.7 167.8 160.8]
     [ 62.   52.   83.   69.   74.   52.   77.   65.   79.   51. ]
     [ 24.   34.   26.   51.   43.   33.   22.   21.   19.   34. ]]
    [48.1 46.8 49.3 51.2 48.7 49.  50.6 47.1 51.7 47.8]