利用python的matplotlib模块作图
程序员文章站
2024-03-26 12:36:59
...
Matplotlib是Python的绘图库,在日常工作和科研活动中经常需要用到,本博文会不定期更新一些常见的画图实例。
一、画散点图
给出一些点坐标,在二维坐标系上表示出来
import matplotlib.pyplot as plt #pyplot子模块提供了一系列API帮助画图
x = [2, 5, 8, 10, 14, 17, 22, 24, 27] #提供一系列点坐标
y = [1, 4, 6, 12, 15, 19, 21, 25, 28]
plt.plot(x, y) #作图命令
plt.show() #展示图像,无此命令,则看不到画出的图,且show()函数会
#阻滞程序的运行,即在不关闭弹出的图像下,show()函数后
#面的代码是不会运行的
运行后得到图像
但是发现并不是我们想要的散点图,原因是因为plot( )函数默认的画图格式就是这样的折线图,我们可以通过在plot( )函数里面添加一些参数来控制作图的格式,来达到我们想要的效果
import matplotlib.pyplot as plt
x = [2, 5, 8, 10, 14, 17, 22, 24, 27]
y = [1, 4, 6, 12, 15, 19, 21, 25, 28]
plt.plot(x, y, color="b", linestyle="None", marker="x", linewidth=1.0)
plt.show()
在我们添加了一些参数后,便得到了我们想要的散点图
下面贴上更详细的一些控制参数
1. 坐标点的风格:
标记 | 含义 | 效果 | 标记 | 含义 | 效果 |
---|---|---|---|---|---|
o | 圆圈 | + | 加号 | ||
< | 朝左三角 | d | 小菱形 | ||
H | 大六边形 | x | ✘号 | ||
. | 点 | v | 朝下三角 | ||
> | 朝右三角 | s | 正方形 | ||
h | 小六边形 | None或, | 无标记 | ||
* | 星号 | ^ | 朝上三角 | ||
D | 大菱形 | p | 五边形 |
2. 线条的风格
标记 | 含义 | 效果 | 标记 | 含义 | 效果 |
---|---|---|---|---|---|
-或默认 | 实线 | : | 虚线 | ||
– | 短横线 | -. | 点画线 | ||
None 或 , | 无线条 |
3. 颜色风格
标记 | 含义 | 效果 | 标记 | 含义 | 效果 |
---|---|---|---|---|---|
r | 红 | m | 洋红 | ||
y | 黄 | g | 绿 | ||
c | 青 | b | 蓝 | ||
k | 黑 | w | 白 |
若我们想在图像加上一些标题,则可以如下代码
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei'] #不加此句会报错,原因:plt找不到中文的字体
x = [2, 5, 8, 10, 14, 17, 22, 24, 27]
y = [1, 4, 6, 12, 15, 19, 21, 25, 28]
plt.suptitle("我的画板标题") #给整个板画板加标题
plt.xlabel("横轴标题") #给横坐标加标题
plt.ylabel("纵轴标题") #给横坐标加标题
plt.plot(x, y, color="w", linestyle="-", marker="+", linewidth=1.0)
plt.savefig(r"C:\Users\syzim\Desktop\test.png")
plt.show()
运行代码,生成图像
图画好了,若我们需要保存生成的图像,就可以使用plt.savefig()函数,如下代码
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']
x = [2, 5, 8, 10, 14, 17, 22, 24, 27]
y = [1, 4, 6, 12, 15, 19, 21, 25, 28]
plt.suptitle("我的画板标题")
plt.xlabel("横轴标题")
plt.ylabel("纵轴标题")
plt.plot(x, y, color="w", linestyle="-", marker="+", linewidth=1.0)
plt.savefig(r"C:\Users\syzim\Desktop\test.png") #savefig()函数一定在show()函数之前,否则,
plt.show() #关闭图像窗口后,图像对象也就被释放了,什
#么都保存不到
上一篇: seajs
推荐阅读
-
python matplotlib 作图注意事项
-
Python matplotlib模块的学习
-
利用python的matplotlib模块作图
-
利用python快速删除指定目录下的文件和文件夹
-
Python中matplotlib作图时title标题太长如何换行
-
Python中matplotlib作图时title标题太长如何换行
-
python中常用的正则表达式及re模块函数的总结
-
【python学习笔记】27:scipy中ndimage模块作图像滤波
-
ImportError: No module named matplotlib.pyplot安装模块python
-
用生动的案例一步步带你学会python多线程模块