Matplotlib 可视化

118 阅读1分钟
  1. Matplotlib 是 Python 中一个非常流行的绘图库,广泛用于数据可视化。它能够生成各种类型的图形,从简单的折线图到复杂的3D图形都可以轻松完成。
  • 使用 pip 来安装 matplotlib
pip install matplotlib
  • 引入 matplotlib
import matplotlib.pyplot as plt
  1. 常见图表类型
  • 折线图
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')  # Equal aspect ratio ensures that pie is drawn as a circle.
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()
  1. 保存图表
plt.savefig('figure.png')  # 保存为 PNG 文件
plt.savefig('figure.pdf')  # 保存为 PDF 文件
plt.close()  # 关闭当前图表