【Python系列课程】Matplotlib(二):坐标轴设置与图例——让图表更专业
·
📊 阅读时长:16分钟 | 关键词:Matplotlib、坐标轴标签、刻度设置、spines边框、legend图例、text标注
引言
上篇文章我们画出了第一张图,但光秃秃的——没轴标签、没图例、坐标轴位置也不对。这篇文章把坐标轴"打扮"起来,让你的图表从"能看"变成"好看"。
一、设置坐标轴标签
plt.xlabel() 和 plt.ylabel() 给横纵坐标轴加说明文字:
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
x = np.linspace(-3, 3, 50)
y = np.sin(x)
plt.figure()
plt.plot(x, y)
# 横轴标签
plt.xlabel("这是 x 轴")
# 纵轴标签,设置字体大小
plt.ylabel("这是 y 轴", fontsize=14)
plt.show()
二、设置坐标轴刻度
plt.xticks() 和 plt.yticks() 控制刻度位置和标签:
plt.figure()
plt.plot(x, y)
# 自定义刻度位置和标签
plt.yticks(ticks=[-1, -0.8, -0.5, -0.1, 1],
labels=["a", "b", "c", "d", "e"])
plt.show()
ticks → 刻度点的位置(刻度线画在这些值上)
labels → 刻度点下方显示的文字
更多刻度操作:
# 去掉刻度(轴还在)
plt.figure()
plt.plot(x, y)
plt.xticks(ticks=[])
plt.show()
# 关闭整个坐标体系
plt.figure()
plt.plot(x, y)
plt.axis("off")
plt.show()
# labels 不指定时,默认显示 ticks 的值
plt.figure()
plt.plot(x, y)
new_xticks = np.linspace(-4, 4, 9)
plt.xticks(ticks=new_xticks)
plt.yticks(ticks=[-1, -0.8, -0.5, -0.1, 1])
plt.show()
| 参数 | 说明 |
|---|---|
ticks |
刻度点位置列表(设为 [] 去掉刻度,但轴还在) |
labels |
刻度点标签列表,不指定则显示 ticks 值 |
三、设置坐标边框颜色
Matplotlib 的坐标体系有四个边框:top、bottom、left、right。你可以分别设置它们的颜色——或者干脆隐藏掉。
plt.figure()
plt.plot(x, y)
plt.yticks(ticks=[-1, -0.8, -0.5, -0.1, 1], labels=["a", "b", "c", "d", "e"])
# 获取当前坐标体系
ax = plt.gca()
# 分别设置四个边框的颜色
ax.spines['right'].set_color('None') # 'None' = 隐藏
ax.spines['top'].set_color('None') # 隐藏
ax.spines['left'].set_color('red') # 红色
ax.spines['bottom'].set_color('green') # 绿色
plt.show()
步骤总结:
plt.gca()获取当前坐标体系ax.spines['top/bottom/left/right']获取指定边框.set_color()设置颜色('None'表示隐藏)
四、移动坐标轴(原点居中)
默认坐标轴在左下角,数学图表通常希望坐标轴穿过原点:
plt.figure()
plt.plot(x, y)
plt.yticks(ticks=[-1, -0.8, -0.5, -0.1, 1], labels=['a', 'b', 'c', 'd', 'e'])
ax = plt.gca()
ax.spines['right'].set_color('None')
ax.spines['top'].set_color('None')
ax.spines['left'].set_color('red')
ax.spines['bottom'].set_color('green')
# 把左轴移到 x=0 的位置
ax.spines['left'].set_position(('data', 0))
# 把底轴移到 y=-0.1 的位置
ax.spines['bottom'].set_position(('data', -0.1))
plt.show()
.set_position(('data', value)) 把边框移到数据坐标系中的指定位置——左轴移到 x=0 就成了 y 轴,底轴移到 y=0 就成了 x 轴。
五、指定边框为坐标轴
你也可以不移动边框,而是把"上边"当 x 轴、"右边"当 y 轴:
plt.figure()
plt.plot(x, y)
plt.yticks(ticks=[-1, -0.8, -0.5, -0.1, 1], labels=['a', 'b', 'c', 'd', 'e'])
ax = plt.gca()
ax.spines['right'].set_color('skyblue')
ax.spines['top'].set_color('blue')
ax.spines['left'].set_color('red')
ax.spines['bottom'].set_color('green')
# 把上边框作为 x 轴(刻度显示在上面)
ax.xaxis.set_ticks_position('top')
# 把右边框作为 y 轴(刻度显示在右边)
ax.yaxis.set_ticks_position('right')
plt.show()
六、plt.legend() 创建图例
画了多条线,哪条是哪个?图例来回答。
x = np.linspace(-3, 3, 50)
y1 = 2*x + 1
y2 = np.sin(x)
plt.figure()
# 画线时通过 label 指定图例文字
plt.plot(x, y1, color='blue', label='直线')
plt.plot(x, y2, color='green', label='曲线')
plt.legend(loc='lower right', fontsize=14,
frameon=True, edgecolor='red', facecolor='yellow')
plt.show()
如果画线时没设 label,也可以在 legend() 中指定:
plt.figure()
plt.plot(x, y1, color='blue')
plt.plot(x, y2, color='green')
# 直接指定 labels
plt.legend(labels=['直线', '曲线'])
plt.show()
只显示指定线条的图例:
plt.figure()
line1, = plt.plot(x, y1, color='blue', label='直线')
line2, = plt.plot(x, y2, color='green', label='曲线')
# 只显示第一条线的图例,并改名为 '线条1'
plt.legend(handles=[line1, ], labels=['线条1', ])
plt.show()
💡
plt.plot()返回一个 Line2D 对象列表,用line1,解包取出单条线。
legend 参数速查:
| 参数 | 说明 | 示例 |
|---|---|---|
handles |
绑定的线对象列表 | handles=[line1] |
labels |
图例文字列表 | labels=['直线','曲线'] |
loc |
图例位置 | 'best'(默认), 'upper right', 'lower left' |
fontsize |
字体大小 | 14 |
edgecolor |
图例边框颜色 | 'red' |
facecolor |
图例背景颜色 | 'yellow' |
frameon |
是否显示边框 | True / False |
七、plt.text() 添加文字标注
在图的任意位置写字:
plt.figure()
plt.plot(x, y)
# 在坐标 (1.1, 0.6) 处写 "y=sinx"
plt.text(x=1.1, y=0.6, s="y=sinx", size=16, color="red")
plt.show()
| 参数 | 说明 |
|---|---|
x, y |
文字起始位置(数据坐标) |
s |
文字内容 |
size |
文字大小 |
color |
文字颜色 |
ha |
水平对齐:'left', 'center', 'right' |
va |
垂直对齐:'top', 'center', 'bottom' |
小结
| 步骤 | 函数 | 效果 |
|---|---|---|
| 坐标轴标签 | plt.xlabel() / plt.ylabel() |
告诉读者这是什么轴 |
| 坐标轴刻度 | plt.xticks() / plt.yticks() |
控制刻度位置和显示文字 |
| 边框颜色 | ax.spines[].set_color() |
隐藏多余边框,突出关键轴 |
| 移动坐标轴 | ax.spines[].set_position() |
把轴移到原点(数学图必备) |
| 图例 | plt.legend() |
区分多条线 |
| 文字标注 | plt.text() |
在图上任意位置加说明 |
下一篇文章,我们画三种实战图表——散点图、条形图和热力图,把前面的轴设置技巧全用上。
本文是「Python从入门到数据分析」系列的第 20 篇。关注我,不错过后续更新。
更多推荐

所有评论(0)