Python matplotlib绘制折线图
matplotlib是Python中的一个第三方库。主要用于开发2D图表,以渐进式、交互式的方式实现数据可视化,可以更直观的呈现数据,使数据更具说服力。
一、安装matplotlib
二、matplotlib图像简介
matplotlib的图像分为三层,容器层、辅助显示层和图像层。
1. 容器层主要由Canvas、Figure、Axes组成。
Canvas位于图像的最底层,充当画布的作用。
Figure位于Canvas之上,指画布上的一整张图像。
Axes位于Figure之上,指Figure中的单个图表,一个Figure中可以有一个或多个Axes,即一张图像中可以有一个或多个图表。
2. 辅助显示层是单个图表(Axes)中用来提供辅助信息的层。
辅助显示层主要包括Axes外观(facecolor)、边框线(spines)、坐标轴(axis)、坐标轴名称(axis label)、坐标轴刻度(tick)、坐标轴刻度标签(tick label)、网格线(grid)、图例(legend)、标题(title)等内容。
辅助层可使图像显示更加直观,提高可读性。
3. 图像层指Axes内通过plot、scatter、bar、histogram、pie等函数绘制出的图形。
三、matplotlib绘制折线图
运行结果:
figure(): 创建图像并设置图像的大小等属性,返回一张图像,可以传入很多参数,常用参数有两个。figsize参数传入一个元组(width, height),设置图像的大小。dpi传入一个整数值,设置图像的清晰度。
plot(): matplotlib中绘制折线图的函数。可以传入很多参数,一般传入两个列表,分别是折线图中的x值和y值。上面的例子中用了NBA2020年季后赛James的得分数据。
show(): 展示图像。
在上面的图表中,x坐标值中有中文,首次使用matplotlib绘图时中文无法正常显示。要解决中文显示问题,需要下载安装SimHei字体,下载链接:https://www.zitijia.com/i/281258939050380345.html,或直接搜索SimHei然后找一个正确的网站下载。下载完成后,在Windows下直接解压双击安装。安装完成后删除~/.matplotlib中的缓存文件,并创建配置文件matplotlibrc,将matplotlibrc中的内容设置为如下内容。
操作命令如下截图,完成后图像中就可以正常显示中文了。
使用上面的代码,已经实现了简单的折线图,但展示的效果很差,所以需要进行优化,使图像展示得更好。
四、matplotlib优化折线图
运行结果:
在使用plot()函数绘图时,可以通过c='颜色'来设置折线图的颜色。
scatter(): 绘制散点图。折线图是用直线连接相邻的两个点形成的,但是连成折线后点的显示不明显。scatter可以单独对点进行设置,展示得更明显。
yticks(): 用于设置y轴坐标的范围,传入一个可迭代对象(如range()函数)。最开始绘制的折线图中,图像的y轴坐标范围是数据的范围,坐标原点不是0,使用yticks函数可以设置想要的坐标范围。同理xticks可以用于设置x轴坐标的范围。
grid(): 用于设置图表中的网格线,使用linestyle参数设置网格线的样式,常用的样式有下表中的几种,plot()函数中也可以用linestyle参数设置折线图的样式。使用alpha参数设置网格线的透明度。
样式 | 字符 |
实线 | - |
虚线 | - - |
点划线 | -. |
点虚线 | : |
xlabel(): 用于设置x轴的标签,说明x轴坐标的含义,第一个参数传入需要设置的标签值,后面可以通过其他参数设置显示的效果,如字体大小等。ylabel同理。
title(): 用于设置折线图的标题,说明这张折线图展示的数据。用法同xlabel。
五、matplotlib绘制多条折线图
运行结果:
要在同一张图像中展示多条折线图,多次调用plot()函数就行。每条折线图的颜色、样式等可以分别设置,以便更好地进行区分。
legend(): 展示图例,通过loc参数传入图例在图表中展示的位置,可以传入的值有‘best’, 'upper right', 'upper left', 'lower left', 'lower right', 'right', 'center left', 'center right', 'lower center', 'upper center', 'center',这十一个值分别对应数字0~10,传值时也可以传对应的数字,后面十个值都指定了图例的位置,'best'表示自适应,会自动根据图像的分布在后面的十个值中选择一个,大部分为右上角'upper right'。
为了使用图例,在每次调用plot()函数绘制折线图时,需要使用label参数给折线图添加标签,在图例中展示。有多条折线图时,图例可以用于区分每条折线图表示的含义,如将James的得分和篮板、助攻展示在同一张图中。
六、matplotlib绘制多张折线图
运行结果:
subplots(): 用于在同一张图像中绘制多张图表,通过nrows, ncols两个参数设置图表的张数和排列方式,figsize和dpi同figure()函数。subplots()函数返回两个参数,一个是图像对象fig,一个是可迭代的图表数组axs(类型为numpy中的数组对象)。
每一张图表中的标签、标题、样式、图例等都需要单独设置,为了避免代码过于冗余,可以使用循环。绘制每一张图表时,从axs中取出每一张图表,再调用plot()函数绘图。在设置坐标轴、标签、标题时,使用'set_'开头的方法进行设置,如设置x轴标签用set_xlabel()。
autofmt_xdate(): x轴坐标值自适应倾斜。因为一张图像中有多张图表,x坐标值靠得很近,可能会因重叠造成展示效果差,使用fig对象的autofmt_xdate()方法可以设置自适应倾斜。
以上就是matplotlib实现折线图的简单介绍,更多设置可以参考官网https://matplotlib.org/tutorials/index.html,并多作尝试。