100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > matplotlib数据可视化实战——折线图+散点图

matplotlib数据可视化实战——折线图+散点图

时间:2020-08-03 10:30:55

相关推荐

matplotlib数据可视化实战——折线图+散点图

今天通过几个实践样例学习了使用matplotlib绘制图像。

过程中出现了很多问题,但是都通过查阅资料一一解决了。最后看到绘制好的图像弹出来以后,内心还是有点小激动。

字体调用问题:

1.导入数据库

from matplotlib.font_manager import FontProperties

2.调用本机字体库

myfont=fm.FontProperties(fname=r'C:\Windows\Fonts\simfang.ttf',size=12)#通常在C:\Windows\Fonts下可以找到本机字体,选中其中一个字体,右键-属性,查看文件类型及字体名称,把这两个加到路径中即可,类似C:\Windows\Fonts\simfang.ttf,其中simfang是字体名,ttf是文件类型。

3.之后每次使用字体可之间用myfont代替

plt.xlabel('顾客购买数量(件)',fontproperties=myfont)

绘制折线图

题目描述

代码实现:

import matplotlib.pyplot as pltimport matplotlib.font_manager as fm #用来导入图例from matplotlib.font_manager import FontPropertiesmyfont=fm.FontProperties(fname=r'C:\Windows\Fonts\simfang.ttf',size=12)#进价与零售价basePrice,salePrice=49,75#计算购买num个商品时的单价,买的越多,单价越低def compute(num):return salePrice*(1-0.01*num)numbers=list(range(1,31))#存储顾客购买数量earns=[]#存储商场盈利情况totalConsumption=[]#存储顾客消费总金额saves=[]#存储顾客节省的总金额#根据顾客购买数量计算三组数据for num in numbers:perPrice=compute(num)earns.append(round(num*(perPrice-basePrice),2))totalConsumption.append(round(num*perPrice,2))saves.append(round(num*(salePrice-perPrice),2))#round函数是对数据进行四舍五入,2指保留两位小数#绘制商家盈利和顾客节省的折线图,系统自动分配线条颜色plt.plot(numbers,earns,label='商家盈利')plt.plot(numbers,totalConsumption,label='顾客总消费')plt.plot(numbers,saves,label='顾客节省')#设置坐标轴标签plt.xlabel('顾客购买数量(件)',fontproperties=myfont)#用fontproperties指定中文字体plt.ylabel('金额(元)',fontproperties=myfont)#设置图形标题plt.title('数量-金额关系图',fontproperties=myfont,fontsize=20)#fontsize指定标题字号#创建字体,设置图例plt.legend(prop=myfont)#legend函数来设置图例#计算并标记商家盈利最多的批发数量maxEarn=max(earns)bestNumbers=numbers[earns.index(maxEarn)]#index函数来找出maxEarn在earns中的位置plt.scatter([bestNumbers],[maxEarn],marker='*',color='red',s=120)#用绘制散点图的方式进行标记#使用annotate()函数在指定位置进行文本标注plt.annotate(xy=(bestNumbers,maxEarn),#箭头终点坐标xytext=(bestNumbers-1,maxEarn+200),#箭头起点坐标s=str(maxEarn),#注释文本arrowprops=dict(arrowstyle='<-'))#设置箭头形状plt.show()#显示图像

图像显示:

绘制散点图

题目描述

代码实现

import matplotlib.pyplot as pltimport matplotlib.font_manager as fmfrom matplotlib.font_manager import FontPropertiesmyfont=fm.FontProperties(fname=r'C:\Windows\Fonts\simfang.ttf',size=12)xs=[]ys=[]strengths=[]# 读取文件中的数据with open(r'C:\Users\ht\PycharmProjects\图像绘制用的数据\散点图数据.txt') as fp:for line in fp:x,y,strength=map(int,line.split(','))xs.append(x)ys.append(y)strengths.append(strength)#把文件中的数据分别添加到列表中#绘制散点图for x,y,s in zip(xs,ys,strengths):if s<40:color='r'elif s<70:color='b'else:color='g'plt.scatter(x,y,s=s*3,c=color,marker='*')#这里的s表示散点符号的大小plt.xlabel('长度坐标',fontproperties=myfont,fontsize=10)plt.ylabel('宽\n度\n坐\n标',fontproperties=myfont,fontsize=10,rotation='horizontal')#rotation用来设置文字方向plt.title('商场内信号强度',fontproperties=myfont,fontsize=14)plt.show()

图像显示

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。