Matplotlib相关的核心内容
Matplotlib是Python的2D绘图库,能够生成高质量的静态、交互式和动画可视化效果。其核心特点是:
Figure
(画布)和Axes
(坐标系)的层级对象模型。Matplotlib 的核心设计理念
Matplotlib 采用分层对象模型,核心对象分为四个层级:
- Figure(画布):所有内容的容器,相当于一张白纸。
- Axes(坐标系):真正绘制数据的区域,包含坐标轴、标题、图例等。
- Axis(坐标轴):控制数据范围的显示(如 X 轴和 Y 轴)。
- Artist(元素):所有可见对象(如线条、文本、标记)的基类。
import matplotlib.pyplot as plt # 创建 Figure 和 Axes fig = plt.figure(figsize=(6, 4)) # 画布尺寸:宽6英寸,高4英寸 ax = fig.add_subplot(1, 1, 1) # 添加一个子图
Matplotlib 提供两种主要绘图方式:
快速绘制简单图表,适合交互式环境(如 Jupyter Notebook):
plt.plot([1, 2, 3, 4], [10, 20, 15, 25], 'ro--') # 红色圆圈虚线
plt.title("Simple Line Chart")
plt.xlabel("X-axis")
plt.show()
更灵活,适用于复杂图表:
fig, ax = plt.subplots(figsize=(8, 5))
ax.plot([1, 2, 3, 4], [10, 20, 15, 25], marker='o', linestyle='--', color='blue')
ax.set_title("Advanced Line Chart")
ax.set_xlabel("X-axis")
ax.grid(True)
plt.show()
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(8, 6)) # 设置画布大小
ax = fig.add_subplot(1, 1, 1) # 1行1列的第1个子图
ax.set_xlim(0, 10)
)。Agg
用于生成图片,Tkinter
用于交互式窗口)。fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(8, 6))
# 示例:绘制折线图、散点图和柱状图
x = [1, 2, 3, 4]
y = [10, 20, 15, 25]
ax.plot(x, y, label='Line') # 折线图
ax.scatter(x, y, label='Points') # 散点图
ax.bar(x, y, alpha=0.3, label='Bars') # 柱状图(半透明)
ax.set_title("Combined Plot", fontsize=14)
ax.set_xlabel("X-axis", fontsize=12)
ax.set_ylabel("Y-axis", fontsize=12)
ax.legend(loc='upper left') # 显示图例
ax.grid(linestyle='--', alpha=0.5) # 虚线网格
plt.savefig('plot.png', dpi=300, bbox_inches='tight') # 保存为高分辨率图片
plt.show() # 显示图表
ax.plot(x, y, color='red', linewidth=2, linestyle='--', marker='o')
ax.scatter(x, y, s=50, c='blue', edgecolor='black', alpha=0.7)
ax.bar(categories, values, color='green', width=0.5, edgecolor='black')
ax.hist(data, bins=30, density=True, color='orange', alpha=0.7)
ax.boxplot([data1, data2], vert=True, patch_artist=True)
基本绘图(法二)
(1) 折线图
x = [1, 2, 3, 4] y = [10, 20, 15, 25] plt.plot(x, y, color='blue', linestyle='--', marker='o', label='Data') plt.title("Line Chart") plt.xlabel("X-axis") plt.ylabel("Y-axis") plt.legend() # 显示图例 plt.grid(True) plt.show()
(2) 散点图
plt.scatter(x, y, s=100, c='red', alpha=0.5, label='Points') plt.title("Scatter Plot")
(3) 柱状图
categories = ['A', 'B', 'C'] values = [30, 50, 20] plt.bar(categories, values, color='green', width=0.5)
(4) 直方图
data = np.random.randn(1000) plt.hist(data, bins=30, edgecolor='black')
ax.set_title("My Plot", fontsize=14)
ax.set_xlabel("X Label", fontsize=12)
ax.set_ylabel("Y Label", fontsize=12)
ax.legend(loc='upper right', frameon=False) # 无边框图例
ax.grid(linestyle=':', alpha=0.7) # 虚线网格
plt.plot(x, y, 'ro--')
表示红色圆圈虚线。color=(0.2, 0.5, 0.8)
。ax.set_xlim(0, 5)
ax.set_ylim(0, 30)
fig, axs = plt.subplots(2, 2, figsize=(12, 8))
axs[0, 0].plot(x, y) # 第一行第一列
axs[1, 1].hist(np.random.randn(1000), bins=30) # 第二行第二列
GridSpec
): import matplotlib.gridspec as gridspec
fig = plt.figure()
gs = gridspec.GridSpec(2, 2, width_ratios=[1, 2])
ax1 = fig.add_subplot(gs[0, :]) # 跨两列
ax2 = fig.add_subplot(gs[1, 0])
plt.style.use('ggplot') # 其他选项:seaborn, fivethirtyeight
scatter = ax.scatter(x, y, c=np.random.rand(len(x)), cmap='viridis')
plt.colorbar(scatter, label='Value') # 添加颜色条
ax.annotate('Peak', xy=(3, 25), xytext=(3.5, 28),
arrowprops=dict(facecolor='black', arrowstyle='->'))
ax.text(1, 20, 'Important Point', fontsize=12, color='red')
ax2 = ax.twinx() # 共享X轴,创建第二个Y轴
ax.plot(x, y1, 'g-')
ax2.plot(x, y2, 'b--')
from mpl_toolkits.mplot3d import Axes3D
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X, Y, Z, cmap='plasma')
from matplotlib.animation import FuncAnimation
def update(frame):
line.set_ydata(np.sin(x + frame/10))
ani = FuncAnimation(fig, update, frames=100, interval=50)
plt.style.use('ggplot') # 使用ggplot风格
plt.scatter(x, y, c=z, cmap='viridis')
plt.colorbar() # 显示颜色条
Figure
> Axes
> Axis
> Artist
。ax.plot()
),而非pyplot
函数。实战技巧
- 避免绘图重叠:在 Jupyter 中运行
%matplotlib inline
后,使用plt.close()
清除内存中的图表。- 处理中文显示:
plt.rcParams['font.sans-serif'] = ['SimHei'] # Windows plt.rcParams['axes.unicode_minus'] = False # 解决负号显示问题
- 动态更新图表:在循环中使用
plt.pause(0.1)
实现简单动画。结合Pandas使用
import pandas as pd df = pd.DataFrame({'x': [1, 2, 3], 'y': [4, 5, 1]}) df.plot(x='x', y='y', kind='line', ax=ax) # 直接使用DataFrame绘图