ubuntuusers.de

[matplotlib] Mehrere Graphen in einer Datei inklusive Text

Status: Gelöst | Ubuntu-Version: Kein Ubuntu
Antworten |

Developer92 Team-Icon

Avatar von Developer92

Anmeldungsdatum:
31. Dezember 2008

Beiträge: 4101

Hallo,

ich habe folgendes Problem: Ich möchte mittels matplotlib und python3 mehrere Graphen erstellen und ein gewisses „Compositing“ durchführen. Im Anhang dazu ein kleines Mockup.

Mein Problem ist, dass ich zwar einzelne Graphen erstellen kann, aber nicht weiß, wie ich mehrere von einander unabhängige Graphen erstellen kann sowie zusätzliche Dinge wie horizontale Linien um die einzelnen Graphen voneinander zu separieren oder auch zusätzlichen Text (beispielsweise seperat Angaben die nichts mit den Grafiken zu tun hat).

Ziel ist es aus einer Datenbank ein paar Daten zu extrahieren um daraus, automatisiert, eine nette Grafik zu basteln (das ganze wird letztlich als png exportiert und soll auf einer Webseite angezeigt werden).

Weiß jemand, wie ich das bewerkstelligen kann? Mittels subplots erreiche ich im Moment lediglich, dass ein Graph über den anderen gezeichnet wird oder ein Koordinatensystem für mehrere Dinge für mehrere Graphen genutzt wird.

Hier noch das aktuelle Skript:

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

## Imports
import os
import urllib
# External
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.font_manager as fontManager

def main():
    # Export-folder
    if not os.path.exists('export'):
            os.makedirs('export')
    # Get font
    url = 'http://antiyawn.com/uploads/Humor-Sans-1.0.ttf'
    if not os.path.exists('Humor-Sans.ttf'):
        urllib.request.urlretrieve(url, 'Humor-Sans.ttf')

    ## General setup
    # Get font
    prop = fontManager.FontProperties(fname='Humor-Sans.ttf', size=16)
    # Set matplotlib params
    #mpl.rcParams['font.family'] = prop.get_name() # doesn't work
    mpl.rcParams.update({'figure.autolayout':True}) # creates extra space for lables (otherwise they would be cut off)
    plt.xkcd() # set to xkcd-style
    fig = plt.figure(1) # ?
    fig.set_figwidth(600/96) # set width to (600px/96dpi) inches
    
    ## Plot 1 weekday
    # Data
    data = [9515,
            11495,
            9093,
            8199,
            7597,
            7526,
            8592]
    legend = ['',
              'Monday',
              'Tuesday',
              'Wednesday',
              'Thursday',
              'Friday',
              'Saturday',
              'Sunday']
    # Setup
    ax1 = fig.add_subplot(1, 1, 1) # 1 row, 1 column, positon 1
    ax1.spines['right'].set_color('none') # remove right border
    ax1.yaxis.set_ticks_position('left') # set ticks to left side only
    ax1.spines['top'].set_color('none') # remove top border
    ax1.xaxis.set_ticks_position('bottom') # set ticks to bottom only
    ax1.set_title('Requests based on weekday', fontproperties=prop) # set title
    ax1.set_ylabel('Number of requests', fontproperties=prop) # set title of y-axis
    #plt.xticks([0,1,2,3,4,5,6], legend, rotation=30) # draw weekdays
    ax1.set_xticklabels(legend, rotation=30, ha='right')  # draw weekdays instead of numbers
    ax1.plot(range(0, 7), data, '-o')
    ax1.set_xlim([-0.5, 6.5])
    ax1.set_ylim([0, max(data)*1.1])
    # Adjust font
    for label in (ax1.get_xticklabels() + ax1.get_yticklabels()):
        label.set_fontproperties(prop)
    
    ## Plot 2 hour
    # Data
    data = [1835,
            1447,
            1802,
            1464,
            1490,
            1341,
            1644,
            2208,
            2548,
            2773,
            3195,
            2925,
            3065,
            2991,
            3315,
            3384,
            3515,
            3020,
            3982,
            3057,
            3069,
            2531,
            2743,
            2673]
    # Setup
    fig = plt.figure(2) # ?
    fig.set_figwidth(600/96) # set width to (600px/96dpi) inches
    ax2 = fig.add_subplot(1, 1, 1) # 1 row, 1 column, positon 2
    ax2.spines['right'].set_color('none') # remove right border
    ax2.yaxis.set_ticks_position('left') # set ticks to left side only
    ax2.spines['top'].set_color('none') # remove top border
    ax2.xaxis.set_ticks_position('bottom') # set ticks to bottom only
    ax2.set_title('Requests based on hours of day', fontproperties=prop) # set title
    ax2.set_ylabel('Number of requests', fontproperties=prop) # set title of y-axis
    #ax2.set_xticklabels(legend, rotation=30, ha='right')  # draw weekdays instead of numbers
    ax2.plot(range(0, 24), data, '-o')
    ax2.set_xlim([-0.5, 24.5])
    ax2.set_ylim([0, max(data)*1.1])
    # Adjust font
    for label in (ax2.get_xticklabels() + ax2.get_yticklabels()):
        label.set_fontproperties(prop)

    ## Save
    fig.savefig('export/graph.png', dpi=96) #, bbox_inches='tight')

if __name__ == '__main__':
    main()
Bilder

noisefloor Team-Icon

Anmeldungsdatum:
6. Juni 2006

Beiträge: 29567

Developer92 Team-Icon

(Themenstarter)
Avatar von Developer92

Anmeldungsdatum:
31. Dezember 2008

Beiträge: 4101

noisefloor schrieb:

Hallo,

mit dem Suchbegriff matplotlib multiple graphs in one plot findet Google u.a.:

Ist doch das, was du suchst, oder?

Eigentlich ja (zugegebenermaßen hab ich das auch selbst gefunden, nur eben nicht verstanden).

Um der Verwirrung etwas Einhalt zu gebieten: Jede Zeichnung kann nur ein figure beinhalten, jedes figure aber mehrere axes (wobei axes das ist, was man in der Regel als Plot bezeichnet) und jede axes mehrere axis (deren Plural blöderweise axes ist) beinhaltet. Von der Namensgebung her also nicht so optimal.

Daher danke, damit komme ich jetzt auch weiter (uns es sieht schon fast so aus, wie ich mir das vorstelle).

Antworten |