Matplotlib 绘图线(Line)完全指南
线(Line) 是 Matplotlib 中最核心的视觉元素,用于连接数据点、展示趋势。本教程带你全面掌握 线型、颜色、宽度、样式、虚线、艺术线 等全部技巧。
一、基本语法
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.plot(x, y, linestyle='-', color='blue', linewidth=2)
plt.show()
二、线型(linestyle)大全
| 线型 | 代码 | 说明 |
|---|---|---|
| 实线 | '-' 或 'solid' | 默认 |
| 虚线 | '--' 或 'dashed' | 常用 |
| 点线 | ':' 或 'dotted' | 细密点 |
| 点划线 | '-.' 或 'dashdot' | 点+划 |
| 无线(仅标记) | 'None' 或 '' | 常用于散点 |
plt.plot(x, y, '--', linewidth=2) # 虚线
三、线宽(linewidth 或 lw)
plt.plot(x, y, linewidth=0.5) # 细线
plt.plot(x, y+1, lw=3) # 粗线
plt.plot(x, y+2, lw=10) # 超粗(强调用)
推荐范围:
0.5 ~ 3.0,论文常用1.0~1.5
四、颜色(color 或 c)
1. 预定义颜色
| 颜色 | 代码 |
|---|---|
| 蓝 | 'b' 或 'blue' |
| 绿 | 'g' |
| 红 | 'r' |
| 青 | 'c' |
| 品红 | 'm' |
| 黄 | 'y' |
| 黑 | 'k' |
| 白 | 'w' |
2. 十六进制 RGB
plt.plot(x, y, color='#1f77b4') # Matplotlib 默认蓝
plt.plot(x, y+1, color='#ff7f0e') # 默认橙色
3. RGBA(带透明度)
plt.plot(x, y, color=(0.1, 0.2, 0.5, 0.7)) # (R, G, B, Alpha)
五、格式字符串快速设置(MATLAB 风格)
plt.plot(x, y, 'r--') # 红色虚线
plt.plot(x, y, 'go-') # 绿色圆点实线
plt.plot(x, y, 'm:') # 品红点线
plt.plot(x, y, 'k-.') # 黑点点划线
顺序:[颜色][标记][线型]
六、虚线模式高级控制(dashes)
自定义 虚线间距(单位:点)
# (线段长度, 间隔长度) 重复
plt.plot(x, y, dashes=[10, 5]) # 长划线 + 小间隙
plt.plot(x, y+1, dashes=[2, 2, 10, 2]) # 点-点-长划-点
plt.plot(x, y+2, dashes=[5, 2, 15, 2]) # 自定义节奏
常用模式:
[8, 4]→ 标准虚线[4, 4]→ 点划线替代[1, 2]→ 极细点线
七、线条样式参数全集
plt.plot(x, y,
color='blue',
linewidth=2,
linestyle='--',
dashes=[10, 4], # 自定义虚线
alpha=0.8, # 透明度
solid_capstyle='round', # 实线端点样式
dash_capstyle='butt', # 虚线端点
drawstyle='default', # 绘图方式
label='sin(x)')
八、多线绘图技巧
plt.plot(x, np.sin(x), 'b-', label='sin(x)')
plt.plot(x, np.cos(x), 'r--', label='cos(x)')
plt.plot(x, x**2/20, 'g:', label='x²/20')
plt.legend()
plt.show()
批量设置(推荐)
lines = plt.plot(x, np.sin(x), x, np.cos(x), x, x**2/20)
plt.setp(lines, linewidth=2) # 统一设置
九、艺术线型(drawstyle)
| 样式 | 效果 |
|---|---|
'default' | 正常连接 |
'steps-pre' | 阶梯(前置) |
'steps-mid' | 阶梯(中间) |
'steps-post' | 阶梯(后置) |
x_step = np.linspace(0, 10, 10)
y_step = np.sin(x_step)
plt.plot(x_step, y_step, drawstyle='steps-pre', linewidth=3)
plt.scatter(x_step, y_step, color='red', zorder=5)
plt.show()
十、完整示例:专业多线图
import matplotlib.pyplot as plt
import numpy as np
plt.style.use('seaborn-v0_8')
x = np.linspace(0, 10, 200)
# 创建画布
fig, ax = plt.subplots(figsize=(12, 7))
# 多条线 + 不同样式
ax.plot(x, np.sin(x), color='#1f77b4', linewidth=3, label='sin(x)')
ax.plot(x, np.cos(x), color='#ff7f0e', linewidth=2.5, linestyle='--', label='cos(x)')
ax.plot(x, np.tan(x), color='#2ca02c', linewidth=2, linestyle=':', dashes=[6, 3], label='tan(x)')
ax.plot(x, x**2/20, color='#d62728', linewidth=2, linestyle='-.', label='x²/20')
ax.plot(x, np.exp(-x/5)*3, color='#9467bd', linewidth=3, dashes=[10, 4, 2, 4], label='衰减曲线')
# 美化
ax.set_title('Matplotlib 线型艺术展示', fontsize=16, fontweight='bold', pad=20)
ax.set_xlabel('X 轴', fontsize=12)
ax.set_ylabel('Y 轴', fontsize=12)
ax.grid(True, alpha=0.3, linestyle='--')
ax.legend(loc='upper left', frameon=True, fancybox=True, shadow=True)
# 坐标轴优化
ax.set_xlim(0, 10)
ax.set_ylim(-3, 5)
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
plt.tight_layout()
plt.savefig('line_styles_pro.png', dpi=300, bbox_inches='tight')
plt.show()
十一、线型速查表(收藏用)
LINE_STYLES = {
'solid': ('-', '实线'),
'dashed': ('--', '虚线'),
'dotted': (':', '点线'),
'dashdot': ('-.', '点划线'),
'long_dash': ([8, 3], '长虚线'),
'dash_dot_dot': ([2, 2, 6, 2], '点-点-划'),
'loose_dotted': ([1, 4], '稀疏点线'),
'steps': ('steps-pre', '阶梯线')
}
十二、常见问题解决
| 问题 | 解决方案 |
|---|---|
| 线太细看不清 | linewidth=2~3 |
| 颜色对比弱 | 使用 color='#1f77b4' 等高对比色 |
| 虚线太密 | dashes=[10, 5] |
| 多线重叠 | 加 alpha=0.7 或用不同 linestyle |
| 保存后线变模糊 | plt.savefig(..., dpi=300) |
十三、推荐配色方案
# 科学论文配色(Colorblind-friendly)
colors = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b']
for i, color in enumerate(colors):
plt.plot(x, np.sin(x + i), color=color, linewidth=2, label=f'Line {i+1}')
官方文档
- 线型参考:https://matplotlib.org/stable/gallery/lines_bars_and_markers/linestyles.html
- 颜色:https://matplotlib.org/stable/tutorials/colors/colors.html
总结:一键生成艺术线
plt.plot(x, y,
color='#1f77b4',
linewidth=2.5,
linestyle='--',
dashes=[12, 6],
alpha=0.9,
label='优雅虚线')
现在就试试! 复制下面代码,改不同 linestyle 看效果:
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
plt.plot(x, np.sin(x), 'r--', linewidth=3, dashes=[15, 5])
plt.title('艺术虚线')
plt.show()
需要我为你:
- 生成 所有线型的对比图 PNG?
- 制作 可交互的线型选择器?
- 输出 LaTeX/PPT 可用线型表格?
告诉我你的需求!