用matplotlib绘制一个美观的折线图

*开始前请先导入matplotlib库以使用相关模块

假设以下将用random模块随机产生某地区某月30天内的温度,并用折线图绘制出气温变化情况。

1绘制一个简单的折线图

# edited by Lyu
# 仅供学习使用,禁止一切商业用途
import matplotlib.pyplot as plt
import random
plt.figure(figsize=(20,8),dpi=100)  #设置图像长宽,像素密度
y=[random.randint(0,20)for i in range(30)]#设置x,y的数据
x=range(1,31)
plt.plot(x,y)                       #绘制折线图
plt.savefig("./plot")
plt.show()                          #显示折线图

得到如下图形:

onenet平台数据可视化折线图没数据 数据可视化折线图绘制_折线图


但是只看此图难以获得有效的信息,我们需要添加一些描述的信息。

2改变刻度(ticks)、增加标签(labels)

# edited by Lyu
# 仅供学习使用,禁止一切商业用途
import matplotlib.pyplot as plt
import random
plt.figure(figsize=(20,8),dpi=100)  #设置图像长宽,像素密度
y=[random.randint(0,20)for i in range(30)]#设置x,y的数据
x=range(1,31)
plt.plot(x,y)                       #绘制折线图
plt.xticks(x)                       #设置x刻度
plt.xlabel("D")                     #设置x标签
plt.ylabel("T")                     #设置y标签
#plt.savefig("./plot")              #保存图片
plt.show()                          #显示折线图

onenet平台数据可视化折线图没数据 数据可视化折线图绘制_机器学习_02


这时可以比较清楚的看清x,y轴表示的信息以及每一日的温度了。

但是matplotlib默认不支持显示中文字符,如果想增加中文信息要怎么办呢?

3增加中文信息

way1:利用系统自带的文字库

# edited by Lyu
# 仅供学习使用,禁止一切商业用途
import matplotlib.pyplot as plt
import random
from matplotlib.font_manager import FontProperties

font = FontProperties(fname="C:\Windows\Fonts\msyh.ttc")
plt.figure(figsize=(20,8),dpi=100)  #设置图像长宽,像素密度
y=[random.randint(0,20)for i in range(30)]#设置x,y的数据
x=range(1,31)
plt.plot(x,y)                       #绘制折线图
x_ticks=["第{}天".format(i) for i in x]#设置x轴刻度标签
plt.xticks(x,x_ticks,fontproperties=font)   #将x数据和刻度标签对应                  #设置x刻度
plt.xlabel("天数",color='r',size=14,fontproperties=font) #设置x、y标签                    #设置x标签
plt.ylabel("温度",color='r',size=14,fontproperties=font)                 #设置y标签
plt.savefig("./plot")              #保存图片
plt.show()                          #显示折线图

onenet平台数据可视化折线图没数据 数据可视化折线图绘制_机器学习_03


way2:利用字典

# edited by Lyu
# 仅供学习使用,禁止一切商业用途
import matplotlib.pyplot as plt
import random

font_dict={'family':'STZhongsong','size':14}#设置font字典,宋体
plt.figure(figsize=(20,8),dpi=100)  #设置图像长宽,像素密度
y=[random.randint(0,20)for i in range(30)]#设置x,y的数据
x=range(1,31)
plt.plot(x,y)                       #绘制折线图
x_ticks=["第{}天".format(i) for i in x]#设置x轴刻度标签
plt.xticks(x,x_ticks,rotation=45,fontdict=font_dict)   #将x数据和刻度标签对应                  #设置x刻度
plt.xlabel("天数",color='r',size=14,fontdict=font_dict) #设置x、y标签                    #设置x标签
plt.ylabel("温度",color='r',size=14,fontdict=font_dict)                 #设置y标签
plt.savefig("./plot")              #保存图片
plt.show()                          #显示折线图

onenet平台数据可视化折线图没数据 数据可视化折线图绘制_python_04


此两种方法比较推荐。此外还有两种方法不太建议,此处不列出。

end