Matplotlib 是 Python 中一个非常流行的绘图库,广泛用于数据可视化。它能够生成各种类型的图形,从简单的折线图到复杂的3D图形都可以轻松完成。
pip install matplotlib
import matplotlib.pyplot as plt
- 常见图表类型
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]
plt.plot(x, y, marker='o')
plt.title('Line Chart Example')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.grid()
plt.show()
x = [5, 7, 8, 10, 12]
y = [12, 14, 15, 20, 24]
plt.scatter(x, y, color='red')
plt.title('Scatter Plot Example')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.show()
categories = ['A', 'B', 'C', 'D']
values = [5, 7, 3, 4]
plt.bar(categories, values)
plt.title('Bar Chart Example')
plt.xlabel('Categories')
plt.ylabel('Values')
plt.show()
sizes = [15, 30, 45, 10]
labels = ['Label A', 'Label B', 'Label C', 'Label D']
colors = ['gold', 'lightcoral', 'lightskyblue', 'yellowgreen']
plt.pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%', startangle=140)
plt.title('Pie Chart Example')
plt.axis('equal')
plt.show()
import numpy as np
随机数据
data = np.random.randn(1000)
创建直方图
plt.hist(data, bins=30, alpha=0.7, color='blue')
添加标题和标签
plt.title('Histogram Example')
plt.xlabel('Value')
plt.ylabel('Frequency')
显示图表
plt.show()
随机数据
data = [np.random.normal(0, std, 100) for std in range(1, 4)]
创建箱线图
plt.boxplot(data, vert=True, patch_artist=True)
添加标题和标签
plt.title('Box Plot Example')
plt.ylabel('Values')
plt.xticks([1, 2, 3], ['Group 1', 'Group 2', 'Group 3'])
显示图表
plt.show()
- 保存图表
plt.savefig('figure.png')
plt.savefig('figure.pdf')
plt.close()