我想在一個圖中繪制多個圖。
為了繪制一組資料,我定義了一個回傳 ax 的函式:
def make_plot(y_true, y_pred, plot_size) :
fig = plt.figure(figsize=(plot_size))
ax = fig.add_subplot(1,1,1)
ax.plot(y_true, y_pred, 'o')
ax.set_xlabel('Observed', size=14)
ax.set_ylabel('Predicted', size=14)
ax.tick_params(labelsize=12)
return ax
然后,我對資料進行 For 回圈,為每組資料繪制一個圖,并將所有圖組合成一個圖形。以下是代碼:
import matplotlib.pyplot as plt
import math
def make_plot(y_true, y_pred, plot_size) :
fig = plt.figure(figsize=(plot_size))
ax = fig.add_subplot(1,1,1)
ax.plot(y_true, y_pred, 'o')
ax.set_xlabel('Observed', size=14)
ax.set_ylabel('Predicted', size=14)
ax.tick_params(labelsize=12)
return ax
def plot_all(y_true_all, y_pred_all, fig_save_folder, fig_name, plot_size=(4,4), num_plots_x = 2):
num_plots_y = math.ceil(len(y_true_all)/num_plots_x) # No. of plots in y direction
plt.figure(figsize=(plot_size[0]*num_plots_x, plot_size[1]*num_plots_y))
for i in range(len((y_true_all))):
ax = plt.subplot(num_plots_y, num_plots_x, i 1) # [row, column]
y_true = y_true_all[i]
y_pred = y_pred_all[i]
ax = make_plot(y_true, y_pred, plot_size)
plt.tight_layout()
plt.savefig(f'{fig_save_folder}/{fig_name}.png')
plt.show()
y_true_all = [[1, 2, 3], [1, 2, 3]]
y_pred_all = [[1.1, 2, 3.1], [1, 1.9, 3]]
fig_save_folder = './result'
fig_name = 'test'
plot_all(y_true_all, y_pred_all, fig_save_folder, fig_name, plot_size=(4,4), num_plots_x = 2)
我想得到的是如下圖:

但是,我得到兩個空軸和一個圖。如果您有任何解決此問題的想法,請告訴我。
uj5u.com熱心網友回復:
將您的函式傳遞給一個更簡單和更好的方法Axes:
import matplotlib.pyplot as plt
import math
def make_plot(y_true, y_pred, ax) :
ax.plot(y_true, y_pred, 'o')
ax.set_xlabel('Observed', size=14)
ax.set_ylabel('Predicted', size=14)
ax.tick_params(labelsize=12)
return ax
def plot_all(y_true_all, y_pred_all, fig_save_folder, fig_name, plot_size=(4,4), num_plots_x = 2):
num_plots_y = math.ceil(len(y_true_all)/num_plots_x) # No. of plots in y direction
plt.figure(figsize=(plot_size[0]*num_plots_x, plot_size[1]*num_plots_y))
for i in range(len((y_true_all))):
ax = plt.subplot(num_plots_y, num_plots_x, i 1) # [row, column]
y_true = y_true_all[i]
y_pred = y_pred_all[i]
ax = make_plot(y_true, y_pred, ax)
plt.tight_layout()
plt.savefig(f'{fig_save_folder}/{fig_name}.png')
plt.show()
y_true_all = [[1, 2, 3], [1, 2, 3]]
y_pred_all = [[1.1, 2, 3.1], [1, 1.9, 3]]
fig_save_folder = './result'
fig_name = 'test'
plot_all(y_true_all, y_pred_all, fig_save_folder, fig_name, plot_size=(4,4), num_plots_x = 2)
輸出:

轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/374571.html
標籤:Python matplotlib 阴谋
上一篇:在圖形的每個頂點上放置點(圖)
