matplotlib 入门

一、什么是 matplotlib

matplotlib: 最流行的Python底层绘图库,主要做数据可视化图表,名字取材于MATLAB,模仿MATLAB构建

二、上手案例

假设一天中每隔两个小时(range(2,26,2))的气温(℃)分别是[15,13,14.5,17,20,25,26,26,27,22,18,15]
在这里插入图片描述

from matplotlib import pyplot as plt
x = range(2,26,2)
y = [15,13,14.5,17,20,25,26,26,27,22,18,15]
plt.plot(x, y)
plt.show()

在这里插入图片描述

三、方法

1、设置图片大小
fig = plt.figure(figsize=(a, b), dpi=dpi)
  • figsize 设置图形的大小,a 为图形的宽, b 为图形的高,单位为英寸
  • dpi 为设置图形每英寸的点数,Matplotlib 中 每英寸点数(ppi)为72
2、保存图片
plt.savefig("hello.png")
# 也可以保存为svg格式,放大后不会有锯齿
3、调整刻度

xticks()传入一个数组

plt.xticks(x)	# 设置所有x坐标
# plt.xticks(x[::2]) 当刻度太密集时,使用列表的步长(间隔取值)来解决,matplotlib自动帮我们对应
plt.yticks(y)   # 设置所有y坐标
4、修改坐标字符串

xticks()传入两个参数,第一个是个数组,第二个是等长列表

from matplotlib import pyplot as plt
import random
y = [random.randint(20,35) for i in range(121)]
x = range(121)
x1, x2 = [(12+i//60) for i in x], [(i % 60) for i in x]
x3 = ["{:02d}:{:02d}".format(x1[i],x2[i]) for i in x]
fig = plt.figure(figsize= (18, 8), dpi= 80)
plt.plot(x, y)
plt.xticks(x[::5], x3[::5])
plt.yticks(range(min(y),max(y)+1))
plt.show()

在这里插入图片描述

5、旋转

xticks()添加形参rotation,表示坐标字符串旋转的度数

plt.xticks(x[::5], x3[::5], rotation = 45)

在这里插入图片描述

6、显示中文

matplotlib默认不支持中文显示,需要手动指定中文字体位置和样式

from matplotlib import pyplot as plt, font_manager
import random
# 这里可以接收的参数:family,style,variant,weight,stretch,size,fname
my_font = font_manager.FontProperties(fname="C:WINDOWS\FONTS\MSYH.TTC")

y = [random.randint(20,35) for i in range(121)]
x = range(121)
x1, x2 = [(12+i//60) for i in x], [(i % 60) for i in x]
x3 = ["{}点{}分".format(x1[i],x2[i]) for i in x]
fig = plt.figure(figsize= (18, 8), dpi= 80)
plt.plot(x, y)
# 手动指定字体
plt.xticks(x[::5], x3[::5], rotation = 45, fontproperties=my_font)
plt.yticks(range(min(y),max(y)+1))
plt.show()

在这里插入图片描述
字体的位置,在设置里可以看到:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
注意!有些字体不能商用

7、添加描述信息
plt.xlabel("时间", fontproperties = my_font)
plt.ylabel("温度 单位(℃)", fontproperties = my_font)
plt.title("12点到14点的气温变化情况", fontproperties = my_font)

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值