Matplotlib Subplots
Zobrazit více pozemků
Pomocí subplots()
funkce můžete nakreslit více grafů v jednom obrázku:
Příklad
Nakreslete 2 výkresy:
import matplotlib.pyplot as plt
import numpy as np
#plot 1:
x =
np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])
plt.subplot(1, 2, 1)
plt.plot(x,y)
#plot 2:
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30,
40])
plt.subplot(1, 2, 2)
plt.plot(x,y)
plt.show()
Výsledek:
Funkce subplots().
Funkce subplots()
přebírá tři argumenty, které popisují rozložení obrázku.
Rozvržení je organizováno do řádků a sloupců, které jsou reprezentovány prvním a druhým argumentem.
Třetí argument představuje index aktuálního grafu.
plt.subplot(1, 2, 1)
#the figure has 1 row, 2 columns, and this plot is the first plot.
plt.subplot(1, 2, 2)
#the figure has 1 row, 2 columns, and this plot is the second plot.
Pokud tedy chceme obrázek se 2 řádky a 1 sloupcem (to znamená, že dva grafy budou zobrazeny nad sebou namísto vedle sebe), můžeme napsat syntaxi takto:
Příklad
Nakreslete 2 grafy na sebe:
import matplotlib.pyplot as plt
import numpy as np
#plot 1:
x =
np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])
plt.subplot(2, 1, 1)
plt.plot(x,y)
#plot 2:
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30,
40])
plt.subplot(2, 1, 2)
plt.plot(x,y)
plt.show()
Výsledek:
Na jeden obrázek můžete nakreslit tolik grafů, kolik chcete, stačí určit počet řádků, sloupců a index výkresu.
Příklad
Nakreslete 6 výkresů:
import matplotlib.pyplot as plt
import numpy as np
x = np.array([0,
1, 2, 3])
y = np.array([3, 8, 1, 10])
plt.subplot(2, 3, 1)
plt.plot(x,y)
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30,
40])
plt.subplot(2, 3, 2)
plt.plot(x,y)
x = np.array([0, 1,
2, 3])
y = np.array([3, 8, 1, 10])
plt.subplot(2, 3, 3)
plt.plot(x,y)
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])
plt.subplot(2, 3, 4)
plt.plot(x,y)
x = np.array([0, 1, 2, 3])
y =
np.array([3, 8, 1, 10])
plt.subplot(2, 3, 5)
plt.plot(x,y)
x
= np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])
plt.subplot(2,
3, 6)
plt.plot(x,y)
plt.show()
Výsledek:
Titul
Ke každému pozemku můžete přidat název pomocí title()
funkce:
Příklad
2 pozemky s názvy:
import matplotlib.pyplot as plt
import numpy as np
#plot 1:
x =
np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])
plt.subplot(1, 2, 1)
plt.plot(x,y)
plt.title("SALES")
#plot 2:
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30,
40])
plt.subplot(1, 2, 2)
plt.plot(x,y)
plt.title("INCOME")
plt.show()
Výsledek:
Super titulek
K celé postavě můžete přidat název pomocí suptitle()
funkce:
Příklad
Přidejte název pro celý obrázek:
import matplotlib.pyplot as plt
import numpy as np
#plot 1:
x =
np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])
plt.subplot(1, 2, 1)
plt.plot(x,y)
plt.title("SALES")
#plot 2:
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30,
40])
plt.subplot(1, 2, 2)
plt.plot(x,y)
plt.title("INCOME")
plt.suptitle("MY SHOP")
plt.show()
Výsledek: