Python 优雅绘图
使用python实验的时候需要绘制各种结果图,这里将介绍如何使用常用的绘图包进行绘图
参考资料:Matplotlib 教程 | 菜鸟教程 (runoob.com)
画图的关键元素包括
- 数据
- 图例
- 线型
- 坐标轴
- 表头
- 网格,辅助线(看情况)
快速入门
简单二维曲线图
这里使用numpy 里面的张量和 matplotlib 来简单绘制图形,简单的图形只需要确定坐标轴和数据就可以了。
1 2 3 4 5 6 7 8 9 10 11
| import matplotlib.pyplot as plt import numpy as np
xpoints = np.array([0, 6]) ypoints = np.array([0, 100])
plt.plot(xpoints, ypoints)
plt.show()
|
常用的绘图类型
1 2 3 4 5 6 7
| plot():用于绘制线图和散点图 scatter():用于绘制散点图 bar():用于绘制垂直条形图和水平条形图 hist():用于绘制直方图 pie():用于绘制饼图 imshow():用于绘制图像 subplots():用于创建子图
|
线图
1 2 3 4 5 6 7 8 9 10 11
| plt.plot(x, y, [fmt2])
plt.plot(x1, y1, [fmt], x2, y2, [fmt2])
plt.plot(x, y, [fmt2]) plt.plot(x, y, [fmt2])
颜色字符:'b' 蓝色,'m' 洋红色,'g' 绿色,'y' 黄色,'r' 红色,'k' 黑色,'w' 白色,'c' 青绿色,'#008000' RGB 颜色符串。多条曲线不指定颜色时,会自动选择不同颜色。 线型参数:'‐' 实线,'‐‐' 破折线,'‐.' 点划线,':' 虚线。 标记字符:'.' 点标记,',' 像素标记(极小点),'o' 实心圈标记,'v' 倒三角标记,'^' 上三角标记,'>' 右三角标记,'<' 左三角标记...等等。
|
此外还可以点的类型,具体看推荐文档
坐标轴
1 2
| plt.xlabel("x - label") plt.ylabel("y - label")
|
表题
如何使用中文字体见参考资料
网格线
1 2 3 4 5 6
| plt.grid() plt.grid(axis='x') plt.grid(axis='y')
plt.grid(color = 'r', linestyle = '--', linewidth = 0.5)
|
绘制多个子图
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| import matplotlib.pyplot as plt import numpy as np
xpoints = np.array([0, 6]) ypoints = np.array([0, 100])
plt.subplot(1, 2, 1) plt.plot(xpoints,ypoints) plt.title("plot 1")
x = np.array([1, 2, 3, 4]) y = np.array([1, 4, 9, 16])
plt.subplot(1, 2, 2) plt.plot(x,y) plt.title("plot 2")
plt.suptitle("RUNOOB subplot Test") plt.show()
|
图例说明
图例属性 参考 matplotlib.pyplot.legend()参数详解_pyplot legend-CSDN博客
legend 的loc 的属性
| upper left |
upper center |
upper right |
| center left |
center |
center right |
| lower left |
lower center |
lower right |
1 2 3 4 5 6 7 8
| plt.plot(x, y1, label='Line 1') plt.plot(x, y2, label='Line 2')
plt.legend()
plt.legend(loc='upper right')
|
快捷模板
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| import matplotlib.pyplot as plt import numpy as np
xpoints = np.array([0, 6]) xpoints2 = np.array([0,3 ]) ypoints = np.array([0, 100])
plt.plot(xpoints, ypoints,'-.b',label='line_1') plt.plot(xpoints2, ypoints,'-y',label='line_1')
plt.legend(loc='center right',fontsize='small')
plt.title('test title')
plt.xlabel("x - label") plt.ylabel("y - label")
plt.show()
|