2015-07-30 18 views
23

Ich bin ein wenig verwirrt darüber, wie dieser Code funktioniert:Wie bekomme ich mehrere Subplots in Matplotlib?

fig, axes = plt.subplots(nrows=2, ncols=2) 
plt.show() 

Wie funktioniert die Feige, die Arbeit in diesem Fall Achsen? Was tut es?

Auch warum nicht diese Arbeit die gleiche Sache zu tun:

fig = plt.figure() 
axes = fig.subplots(nrows=2, ncols=2) 

Dank

Antwort

39

Es gibt mehrere Möglichkeiten, dies zu tun. Die subplots Methode erstellt die Abbildung zusammen mit den Unterplots, die dann im ax Array gespeichert werden. Zum Beispiel:

import matplotlib.pyplot as plt 

x = range(10) 
y = range(10) 

fig, ax = plt.subplots(nrows=2, ncols=2) 

for row in ax: 
    for col in row: 
     col.plot(x, y) 

plt.show() 

enter image description here

jedoch so etwas wie dies auch funktionieren wird, ist es nicht so „sauber“, obwohl, da Sie eine Figur mit Nebenhandlungen erstellen und fügen Sie dann auf sie:

fig = plt.figure() 

plt.subplot(2, 2, 1) 
plt.plot(x, y) 

plt.subplot(2, 2, 2) 
plt.plot(x, y) 

plt.subplot(2, 2, 3) 
plt.plot(x, y) 

plt.subplot(2, 2, 4) 
plt.plot(x, y) 

plt.show() 

enter image description here

+0

Statt 'plot (x, y)' Ich habe meine Handlung aus einer benutzerdefinierten Funktion kommen, die ein Diagramm mit NetworkX schafft. Wie man es benutzt? – Sigur

7

die Dokumentation zu lesen: matplotlib.pyplot.subplots

pyplot.subplots() gibt ein Tupel fig, ax, die in zwei Variablen ausgepackt wird mit die Notation

fig, axes = plt.subplots(nrows=2, ncols=2) 

der Code

fig = plt.figure() 
axes = fig.subplots(nrows=2, ncols=2) 

funktioniert nicht, weil subplots() ist eine Funktion in pyplot nicht Mitglied des Objekts Figure.

2

Sie könnten in der Tatsache interessiert sein, dass ab matplotlib Version 2.1 der zweite Code von der Frage arbeitet fi auch ne.

Vom change log:

Figur Klasse hat nun Nebenhandlungen Verfahren Die Figur Klasse nun eine Nebenhandlung hat() Methode, die die gleiche wie pyplot.subplots(), aber auf einer bestehende Figur verhält.

Beispiel:

import matplotlib.pyplot as plt 

fig = plt.figure() 
axes = fig.subplots(nrows=2, ncols=2) 

plt.show() 
Verwandte Themen