以下为绘制matplotlib折线图的一些基本操作:
# coding = utf-8
from matplotlib import pyplot as plt
import random
import matplotlib
from matplotlib import font_manager
#windows 和 linux设置字体的方式
# font = {'family' : 'MicroSoft YaHei',
# 'weight' : 'bold',
# 'size' : 'larger'}
# matplotlib.rc("font",**font)
# # matplotlib.rc("font",family='MicroSoft YaHei',weight="bold")
#另外一种设置字体的方式
my_font = font_manager.FontProperties(fname = "C:\\WINDOWS\\FONTS\\MSYHL.TTC")
# x = range(2,26,2)
# y = [15,13,14,5,17,20,25,26,24,22,18,15]
x = range(0,120)
y = [random.randint(20,35) for i in range(120)]
#设置图片大小
plt.figure(figsize = (16,8),dpi = 80)
#绘图
plt.plot(x,y)
#设置x轴的刻度
# _xtick_labels = [i/2 for i in range(4,49)]
# plt.xticks(range(2,25))
# plt.xticks(_xtick_labels)
# plt.yticks(range(min(y),max(y)))
#调整x轴的刻度
# _x = list(x)[::10]
# _xtick_labels = ["hello,{}".format(i) for i in _x]
# plt.xticks(_x,_xtick_labels)
#调整x轴的刻度2
_xtick_labels = ["10点{}分".format(i) for i in range(60)]
_xtick_labels += ["11点{}分".format(i-60) for i in range(60,120)]
# plt.yticks(range(0,9))
#取步长,数字和字符串一一对应,数据长度必须一致
plt.xticks(list(x)[::3],_xtick_labels[::3],rotation = 45,fontproperties = my_font) #rotation
#添加描述信息
plt.xlabel("时间",fontproperties = my_font)
plt.ylabel("温度 单位(摄氏度)",fontproperties = my_font)
plt.title("十点到十二点每分钟气温变化情况",fontproperties = my_font)
#绘制网格
plt.grid(alpha = 0.1)
#展示图形
plt.show()
#保存图片
# plt.savefig("./t1.png")
# plt.savefig("./t1.svg")
两条折线做对比以及一些基本设置:
# coding = utf-8
from matplotlib import pyplot as plt
from matplotlib import font_manager
my_font = font_manager.FontProperties(fname = "C:\\WINDOWS\\FONTS\\MSYHL.TTC")
y_1 = [1,0,1,1,2,4,3,2,3,4,4,5,6,5,4,3,3,1,1,1]
y_2 = [1,0,3,1,2,2,3,3,2,1,2,1,1,1,1,1,1,1,1,1]
x = range(11,31)
#设置图形大小
plt.figure(figsize = (20,8),dpi = 80)
plt.plot(x,y_1,label="自己",color="red",linewidth=5)
plt.plot(x,y_2,label="同桌",linestyle=":")
#设置x轴刻度
_xtick_labels = ["{}岁".format(i) for i in x]
plt.xticks(x,_xtick_labels,fontproperties = my_font)
# plt.yticks(range(0,9))
#绘制网格
plt.grid(alpha = 0.3,linestyle="--")
#添加图例
plt.legend(prop=my_font,loc="upper left")
#展示
plt.show()