Matlotlib学习笔记

斜线图

使用plot函数绘制折线图,可以使用多个plot()函数在同一个坐标系内绘制多个折线图

设置图片大小和保存图片

使用figsize设置图片大小:figsize(宽,高)
使用savefig保存图片,如下:

from matplotlib import pyplot as plt
fig = plt.figure(figsize=(12, 8), dpi=80)  # figsize(wide,height)
x = range(2, 26, 2)
y = [15, 13, 14, 17, 20, 25, 26, 26, 24, 22, 18, 15]
plt.plot(x, y)
# save after plot
plt.savefig("./p1.png")
plt.show() 

设置x轴和y轴刻度

  1. 可以直接将x,y轴的刻度传给xticks和yticks
plt.xticks(x)
plt.yticks(range(min(y), max(y)+1))
  1. 如果想以0.5为x轴间隔:
_xtick_labels = [i/2 for i in range(4,49)] # 0.5 slide
plt.xticks(_xtick_labels)
  1. 调整x轴刻度为实际意义。(10点-12点)
    注:rotation可以调整刻度旋转角度。
x = range(0, 120)
y = [random.randint(20, 35) for i in range(120)]
_xtick_labels = ["10:{}".format(i) for i in range(60)]
_xtick_labels += ["11:{}".format(i) for i in range(60)]
plt.xticks(list(x)[::30], _xtick_labels[::30], rotation=45)

设置x轴y轴标签以及标题

直接使用xlabel、ylabel、title进行设置

plt.xlabel("time")
plt.ylabel("Temperature")
plt.title("Temperature variation from 10:00 to 12:00")

图像显示中文

matplotlib的刻度、标签以及标题都不支持中文字体,要想显示中文,可以通过font_manager进行设置:
注:在legend中是prop=my_font

  1. 在linux/windows/mac下搜索电脑中的中文字体:
    fc-list :lang-zh (注意冒号前有一个空格)
  2. 在python中通过font_manager设置中文,fname传入中文字体路径。然后将font_manager传给fontproperties,加入到xtick、xlabel或title中。
from matplotlib import font_manager
my_font = font_manager.FontProperties(fname="/usr/share/fonts/truetype/arphic/uming.ttc")
plt.xticks(list(x)[::30], _xtick_labels[::30], rotation=45, fontproperties=my_font)

设置折线风格

plot可以设置以下参数
linewidth:线条粗细
alpha:透明度
color:颜色(可直接百度颜色代码使用)
label:图例,要配合legend使用
linestyle:线条风格:实线、虚线等。

plt.plot(x,y,label="label",color="orange",linestyle=":")

显示背景网格

使用plt.grid显示背景网格,alpha参数可以修改透明度

plt.grid(alpha=0.4)

散点图

使用scatter()绘制散点图,其余同折线图
例:画三月和十月的北京市温度日变化

from matplotlib import pyplot as plt
from matplotlib import font_manager
y_3 = [11, 17, 16, 11, 12, 11, 12, 6, 6, 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值