Як створити кілька графіків matplotlib на одній фігурі
Ви можете використовувати наступний синтаксис, щоб створити кілька діаграм Matplotlib на одній фігурі:
import matplotlib. pyplot as plt #define grid of plots fig, axs = plt. subplots (nrows= 2 , ncols= 1 ) #add data to plots axs[0]. plot (variable1, variable2) axs[1]. plot (variable3, variable4)
Наступні приклади показують, як використовувати цю функцію на практиці.
Приклад 1: укладання контурів вертикально
Наступний код показує, як створити три діаграми Matplotlib, складені вертикально:
#create some data
var1 = [1, 2, 3, 4, 5, 6]
var2 = [7, 13, 16, 18, 25, 19]
var3 = [29, 25, 20, 25, 20, 18]
#define grid of plots
fig, axs = plt. subplots (nrows= 3 , ncols= 1 )
#add title
fig. suptitle (' Plots Stacked Vertically ')
#add data to plots
axs[0]. plot (var1, var2)
axs[1]. plot (var1, var3)
axs[2]. plot (var2, var3)
Приклад 2: укладання контурів по горизонталі
Наступний код показує, як створити три діаграми Matplotlib, складені горизонтально:
#create some data
var1 = [1, 2, 3, 4, 5, 6]
var2 = [7, 13, 16, 18, 25, 19]
var3 = [29, 25, 20, 25, 20, 18]
#define grid of plots
fig, axs = plt. subplots (nrows= 1 , ncols= 3 )
#add title
fig. suptitle (' Plots Stacked Horizontally ')
#add data to plots
axs[0]. plot (var1, var2)
axs[1]. plot (var1, var3)
axs[2]. plot (var2, var3)
Приклад 3: Створення сітки графіка
Наступний код показує, як створити сітку графіка Matplotlib:
#create some data
var1 = [1, 2, 3, 4, 5, 6]
var2 = [7, 13, 16, 18, 25, 19]
var3 = [29, 25, 20, 25, 20, 18]
var4 = [4, 4, 6, 4, 7, 11]
#define grid of plots
fig, axs = plt. subplots (nrows= 2 , ncols= 2 )
#add title
fig. suptitle (' Grid of Plots ')
#add data to plots
axs[0, 0]. plot (var1, var2)
axs[0, 1]. plot (var1, var3)
axs[1, 0]. plot (var1, var4)
axs[1, 1]. plot (var3, var1)
Приклад 4: Спільні осі між ділянками
Ви можете використовувати аргументи sharex і sharey , щоб переконатися, що кілька графіків використовують одну вісь x:
#create some data
var1 = [1, 2, 3, 4, 5, 6]
var2 = [7, 13, 16, 18, 25, 19]
var3 = [29, 25, 20, 25, 20, 18]
var4 = [4, 4, 6, 4, 7, 11]
#define grid of plots
fig, axs = plt. subplots (nrows= 2 , ncols= 2 , sharex= True , sharey= True )
#add title
fig. suptitle (' Grid of Plots with Same Axes ')
#add data to plots
axs[0, 0]. plot (var1, var2)
axs[0, 1]. plot (var1, var3)
axs[1, 0]. plot (var1, var4)
axs[1, 1]. plot (var3, var1)
Додаткові ресурси
Як налаштувати відстань між підсхемами Matplotlib
Як змінити колір фону в Matplotlib
Як збільшити розмір графіка в Matplotlib