Matplotlib怎么構(gòu)建復(fù)合圖表布局

小億
85
2024-05-21 14:35:37

在Matplotlib中,可以使用Figure對(duì)象和Axes對(duì)象來(lái)構(gòu)建復(fù)合圖表布局。Figure對(duì)象代表整個(gè)圖表,而Axes對(duì)象則代表單個(gè)子圖。

以下是一個(gè)簡(jiǎn)單的示例,展示如何構(gòu)建一個(gè)包含多個(gè)子圖的復(fù)合圖表布局:

import matplotlib.pyplot as plt
import numpy as np

# 創(chuàng)建Figure對(duì)象和多個(gè)Axes對(duì)象
fig, axs = plt.subplots(2, 2)

# 在第一個(gè)子圖中繪制折線圖
x = np.arange(0, 10, 0.1)
y = np.sin(x)
axs[0, 0].plot(x, y)
axs[0, 0].set_title('Sine Curve')

# 在第二個(gè)子圖中繪制柱狀圖
x = np.arange(5)
y = np.random.randint(1, 10, 5)
axs[0, 1].bar(x, y)
axs[0, 1].set_title('Bar Chart')

# 在第三個(gè)子圖中繪制散點(diǎn)圖
x = np.random.randn(100)
y = np.random.randn(100)
axs[1, 0].scatter(x, y)
axs[1, 0].set_title('Scatter Plot')

# 在第四個(gè)子圖中繪制餅圖
sizes = np.random.randint(1, 10, 5)
labels = ['A', 'B', 'C', 'D', 'E']
axs[1, 1].pie(sizes, labels=labels, autopct='%1.1f%%')
axs[1, 1].set_title('Pie Chart')

plt.tight_layout()
plt.show()

在這個(gè)示例中,我們使用plt.subplots()函數(shù)創(chuàng)建了一個(gè)2x2的子圖布局,然后在每個(gè)子圖中繪制了不同類型的圖表。最后使用plt.tight_layout()函數(shù)調(diào)整子圖之間的間距,并調(diào)用plt.show()展示圖表。

0