绘制折线图的几个小技巧
2018-11-27 本文已影响0人
泡泡坪
折线图通常是用来表达某个数值指标的波动特征,表现的是一种时间维度下的变化。那么问题来了,读者在使用Python绘制时间维度的折线图时是否遇到过这样的问题:怎么让时间轴表现的不拥挤,又能够友好地呈现呢?就如下图的方式:

本期我们就来聊聊Python中关于时间轴的几种处理办法,包括如何控制时间轴呈现的刻度个数、刻度间隔和刻度标签的旋转。
语法介绍
在Python中绘制折线图,需要使用matplotlib模块中的plot函数实现,该函数的具体语法如下:
plt.plot(x, y, linestyle, linewidth, color, marker,
markersize, markeredgecolor, markerfactcolor,
markeredgewidth, label, alpha)
x:指定折线图的x轴数据;
y:指定折线图的y轴数据;
linestyle:指定折线的类型,可以是实线、虚线、点虚线、点点线等,默认文实线;
linewidth:指定折线的宽度
marker:可以为折线图添加点,该参数是设置点的形状;
markersize:设置点的大小;
markeredgecolor:设置点的边框色;
markerfactcolor:设置点的填充色;
markeredgewidth:设置点的边框宽度
label:为折线图添加标签,类似于图例的作用;
刻度个数的控制
首先将该数据读入到Python环境中,并检查数据的数据类型,是否适合绘制折线图。
# 导入第三方包
import pandas as pd
# 数据读取
AQI = pd.read_excel(r'C:\Users\Administrator\Desktop\AQI.xlsx')
# 查看变量的数据类型
AQI.dtypes

如上结果所示,日期变量Date为字符型,不能直接用来绘制图形,需要将其转换为日期型。
# 数据类型转换
AQI.Date = pd.to_datetime(AQI.Date)
接下来基于类型转换后的数据,利用plot函数绘制一个不做任何修饰的折线图:
# 导入第三方模块
import matplotlib.pyplot as plt
# 解决中文乱码问题
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']
# 绘制折线图
plt.plot(AQI.Date, # x轴数据
AQI.AQI, # y轴数据
linestyle = '-', # 折线类型
linewidth = 2, # 折线宽度
color = 'steelblue', # 折线颜色
marker = 'o', # 折线图中添加圆点
markersize = 6, # 点的大小
markeredgecolor='black', # 点的边框色
markerfacecolor='brown') # 点的填充色
# 添加y轴标签
plt.ylabel('AQI')
# 添加图形标题
plt.title('近3个月的空气质量指数')
# 显示图形
plt.show()

如上图所示,图形中的x轴是非常糟糕的,重叠的几乎看不清。必须要对轴作处理,否则无法使用。利用Python对日期型的轴作处理同样非常简单,只需要添加几行关于轴设置的代码即可:
# 导入模块,用于日期刻度的修改
import matplotlib as mpl
plt.plot(AQI.Date, AQI.AQI, linestyle = '-',
linewidth = 2, color = 'steelblue',
marker = 'o', markersize = 6,
markeredgecolor='black',
markerfacecolor='brown')
plt.ylabel('AQI')
plt.title('近3个月的空气质量指数')
# 获取图的坐标信息
ax = plt.gca()
# 设置日期的显示格式 (即“月-日”)
date_format = mpl.dates.DateFormatter("%m-%d")
ax.xaxis.set_major_formatter(date_format)
# 控制x轴显示的日期个数(如10个)
xlocator = mpl.ticker.LinearLocator(10)
ax.xaxis.set_major_locator(xlocator)
plt.show()

如上图所示,我们在原有代码的基础上做了两方面的修改,一个是将日期呈现为“月-日”的格式,这样可以缩短刻度标签;另一个是我们控制了x轴刻度标签的个数(如图中呈现了10个刻度值)。
刻度间隔的控制
除了利用上面的方法控制刻度标签的个数,还可以设置刻度标签之间的固定间隔,如7天或两周等。具体代码如下:
plt.plot(AQI.Date, AQI.AQI, linestyle = '-',
linewidth = 2, color = 'steelblue',
marker = 'o', markersize = 6,
markeredgecolor='black',
markerfacecolor='brown')
plt.ylabel('AQI')
plt.title('近3个月的空气质量指数')
ax = plt.gca()
date_format = mpl.dates.DateFormatter("%m-%d")
ax.xaxis.set_major_formatter(date_format)
# 控制x轴显示日期的间隔天数(如一周7天)
xlocator = mpl.ticker.MultipleLocator(7)
ax.xaxis.set_major_locator(xlocator)
plt.show()

如上图所示,标签值之间形成了固定的间隔,即7天。但是还是存在重叠或拥挤问题,解决的办法有两种,一个是拉长间隔天数,另一个是将刻度标签旋转30度或45度。
刻度标签的旋转
plt.plot(AQI.Date, AQI.AQI, linestyle = '-',
linewidth = 2, color = 'steelblue',
marker = 'o', markersize = 6,
markeredgecolor='black',
markerfacecolor='brown')
plt.ylabel('AQI')
plt.title('近3个月的空气质量指数')
ax = plt.gca()
date_format = mpl.dates.DateFormatter("%m-%d")
ax.xaxis.set_major_formatter(date_format)
# 控制x轴显示日期的间隔天数(如一周7天)
xlocator = mpl.ticker.MultipleLocator(7)
ax.xaxis.set_major_locator(xlocator)
# 为了避免x轴刻度标签的紧凑,将刻度标签旋转45度
plt.xticks(rotation=45)
plt.show()

如上图所示,问题得到了完美的解决。在不修改间隔天数的情况下,简单的旋转刻度标签的角度,就可以解决问题。