matplotlib 学习第一课

这篇文章介绍了使用matplotlib进行数据可视化的基本方法,包括设置图片大小、绘制线图、散点图、条形图和直方图,以及如何处理中文显示和调整坐标轴。还涉及了图形样式、图例和标签的设定,以及图像保存的操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

matplotlib 学习第二课


from matplotlib import pyplot as plt
from matplotlib import font_manager
import random
import matplotlib
my_font=font_manager.FontProperties(fname="C:\Windows\Fonts\AdobeHeitiStd-Regular.otf")

x = range(1,13)
y = [random.randint(20,30) for i in range(12)]
t=["第{}分钟".format(i) for i in range(1,13)]
#设置图片大小
plt.figure(figsize=(20,10),dpi=100)

plt.yticks(range(min(y),max(y)+5))
#绘图
plt.plot(x,y)
plt.xticks(x,t,fontproperties=my_font)
plt.xlabel("时间",fontproperties=my_font)
plt.show()

绘制多个图

plt.plot(x,y_1,label=大地",color="bule",linestyle=":")

plt.plot(x,y_2,label="天空")

plt.legend(prop=my_font,loc="upper left")图例绘制用prop接收字体格式

调整坐标轴刻度

plt.xticks(x[::3]) 设置间距
plt.xticks(x,_xticks_labels,fontproperties=my_font,rotation=90,labels="时间")
设置X轴坐标格式和内容

显示中文

from matplotlib import font_manager
my_font=font_manager.FontProperties(fname="C:\Windows\Fonts\AdobeHeitiStd-Regular.otf") 实例化字体

保存图片

plt.savefig("file_path")

设置图片

plt.figure(figsize=(20,8),dpi=80)

图形样式

plt.plot(x,y,label="自己",color="十六进制代码或是英文名字",linestyle=":")

plt.legend(prop=my_font,loc="upper left") 用于定义参数

绘制网络

plt.grid(alpha=0.4)设置透明度

绘制散点图

from matplotlib import pyplot as plt
from matplotlib import font_manager
my_font=font_manager.FontProperties(fname="C:\Windows\Fonts\AdobeHeitiStd-Regular.otf")

a = [11,17,16,11,12,11,12,6,6,7,8,9,12,15,14,17,18,21,16,17,20,14,15,15,15,19,21,22,22,22,23]
b = [26,26,28,19,21,17,16,19,18,20,20,19,22,23,17,20,21,20,22,15,11,15,5,13,17,10,11,13,12,13,6]
x_1=range(1,32)
x_2=range(41,72)
plt.scatter(x_1,a,label="3月")
plt.scatter(x_2,b,label="10月")

_x=list(x_1)+list(x_2)
_xticks_label=["3月{}日".format(i) for i in x_1]
_xticks_label+=["十月{}日".format(i) for i in x_2]
plt.xticks(_x[::3],_xticks_label[::3],fontproperties=my_font,rotation=90)
plt.legend(prop=my_font)
plt.xlabel("时间",fontproperties=my_font)
plt.ylabel("温度",fontproperties=my_font)
plt.title("温度变化趋势",fontproperties=my_font)
plt.show()

绘制条形图

from matplotlib import pyplot as plt
from matplotlib import font_manager

my_font=font_manager.FontProperties(fname="C:\Windows\Fonts\AdobeHeitiStd-Regular.otf")

a = ["猩球崛起3:终极之战","敦刻尔克","蜘蛛侠:英雄归来","战狼2"]
b_16 = [15746,312,4497,319]
b_15 = [12357,156,2045,168]
b_14 = [2358,399,2358,362]
bar_width=0.2
x=list(range(len(a)))
x_1=[i+bar_width for i in x]
x_2=[i+bar_width*2 for i in x]
plt.bar(x,b_14,width=bar_width,label="9月14")
plt.bar(x_1,b_15,width=bar_width,label="9月15")
plt.bar(x_2,b_16,width=bar_width,label="9月15")
plt.legend(prop=my_font)
plt.xticks(x_1,a,fontproperties=my_font)
plt.show()

绘制直方图

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值