目录
前言
以下分享折线图小案例,matplotlib还可以进行多种图形的绘制,可以进入官网 https://matplotlib.org/gallery/index.html,点击examples,如需学习,选择要学习的图进入,里面包含有代码
python之matplotlib使用系统字体
1.导包from matplotlib.font_manager import FontProperties2.调用本机字体库设置字体my_font=font_manager.FontProperties(fname="C:\\Windows\\Fonts\\msyh.ttc")
其中,msyh.ttc是自己电脑中的字体,如何找到呢?
在路径C:\\Windows\\Fonts的文件夹中,有如下字体,如下图:
绘图的时候,直接调用就好
plt.xticks(list(x)[::3],_xtick_labels[::3],rotatinotallow=45,fnotallow=my_font)
实例1:温度变化统计
#如果列表a便是10点到12点的每一分钟的气温,绘制折线图 # a=[random.randint(20,35)for i in range(120)] #解决中文不显示问题 #fc-list -->查看支持的字体 #fc-list :lang=zh -->查看支持的中文(冒号前有空格) from matplotlib import pyplot as plt import random import matplotlib from matplotlib import font_manager #1.windows\\linux设置字体 #font = {\'family\' : \'MicroSoft YaHei\', # \'weight\' : \'bold\', # \'size\' : \'larger\'} #matplotlib.rc(\"font\",**font) #查看源码ctrl+b #2.另一种设置字体方式 my_font=font_manager.FontProperties(fname=\"C:\\Windows\\Fonts\\msyh.ttc\") #定义x、y轴 x = range(0,120) y = [random.randint(20,35) for i in range(120)] #修改大小尺寸 plt.figure(figsize=(20,8),dpi=80) #绘制 plt.plot(x,y) #调整x轴的刻度 _xtick_labels = [\"10点{}分\".format(i) for i in range(60)] _xtick_labels += [\"11点{}分\".format(i) for i in range(60)] #取适当步长,将数字与x轴字符串对应,使得数据长度保持一致 plt.xticks(list(x)[::3],_xtick_labels[::3],rotation=45,fontproperties=my_font) #将x轴字符串旋转45度 #添加描述信息 plt.xlabel(\"时间\",fontproperties=my_font) plt.ylabel(\"温度 单位(°c)\",fontproperties=my_font) plt.title(\"10点到12点每分钟的气温变化情况\",fontproperties=my_font) #显示图示 plt.show()
实例2:交友数量折线图
#你与朋友从11到30岁交的朋友数,并比较 from matplotlib import pyplot as plt from matplotlib import font_manager #设置字体 my_font=font_manager.FontProperties(fname=\"C:\\Windows\\Fonts\\msyh.ttc\") #定义坐标轴 x = range(11,31) y_1 = [2,3,3,4,6,5,6,5,8,5,4,6,4,4,4,4,4,3,3,3] y_2 = [1,4,5,5,6,4,5,5,4,7,6,5,3,2,2,6,1,2,6,4] #设置图形大小 plt.figure(figsize=(20,8),dpi=80) #绘制 plt.plot(x,y_1) plt.plot(x,y_2) #绘制x\\y轴刻度,添加描述信息 _xtick_labels = [\"{}岁\".format(i) for i in x] plt.xticks(x,_xtick_labels,fontproperties=my_font) plt.yticks(range(0,10)) plt.xlabel(\"年龄\",fontproperties=my_font) plt.ylabel(\"每年交到的新朋友数\",fontproperties=my_font) plt.title(\"与朋友每年新交到朋友数量对比图\",fontproperties=my_font) #绘制网格,并设置透明度 plt.grid(alpha=0.3) #展示 plt.show()
1.这个案例中涉及到一表多图,其实很简单,与单图设计一样,只要再添加一组y轴坐标。
这里x轴是共有的,不需要另行设置。#定义坐标轴
x = range(11,31)
y_1 = [2,3,3,4,6,5,6,5,8,5,4,6,4,4,4,4,4,3,3,3]
y_2 = [1,4,5,5,6,4,5,5,4,7,6,5,3,2,2,6,1,2,6,4]
#绘制
plt.plot(x,y_1)
plt.plot(x,y_2)
2.绘制网格及设置透明度
plt.grid(alpha=0.3)
3.但是当你给别人展示时,并没有源码,别人很难分清哪个曲线是你的,哪个是你朋友的,这时就需要我们添加图例,并且要注意的是:
通常我们设置中文字体是对应方法后添加fontproperties=my_font
,但是在添加图例中用到的是prop=my_font
如图所示:
4.更改图例位置
由于初学,很多方法我们还不是很清楚,所以我们要学会查看源码(选中方法名+ctrl+b)
再使用一次,进入后会找到有关参数loc(location)的描述,我们设置loc=“upper left”,结果如图所示
5.设置曲线颜色,线条样式
#绘制,添加颜色 plt.plot(x,y_1,label=\"自己\",color=\"y\") plt.plot(x,y_2,label=\"朋友\",color=\"cyan\")
#绘制,添加线条类型 plt.plot(x,y_1,label=\"自己\",color=\"purple\",linestyle=\'-.\') plt.plot(x,y_2,label=\"朋友\",color=\"cyan\",linestyle=\'--\')
暂无评论内容