一. 折线图
from matplotlib import pyplot as plt
x = range(2,26,2)
y = [15,13,14.5,17,20,25,26,26,24,22,18,15]
plt.plot(x,y)
plt.show()
二. 基本设置
1. 设置图片大小
from matplotlib import pyplot as plt
fig = plt.figure(figsize=(20,8), dpi = 80)
# figsize可以设置图片大小
# dpi可以设置清晰度
x = range(2,26,2)
y = [15,13,14.5,17,20,25,26,26,24,22,18,15]
plt.plot(x,y)
plt.show()
2.保存图片
from matplotlib import pyplot as plt
fig = plt.figure(figsize=(20,8), dpi = 80)
x = range(2,26,2)
y = [15,13,14.5,17,20,25,26,26,24,22,18,15]
plt.plot(x,y)
plt.savefig("./picture.png")
# 设置保存位置,也可保存为svg矢量图格式(放大不失真)
plt.show()
3. 调整x轴、y轴刻度值
(一). 显示刻度值
from matplotlib import pyplot as plt
fig = plt.figure(figsize=(20,8), dpi = 80)
x = range(2,26,2)
y = [15,13,14.5,17,20,25,26,26,24,22,18,15]
plt.plot(x,y)
plt.xticks(x)
# 以2为起始点,24为结束点,步长间隔为2
# 同理也有plt.yticks()
plt.show()
(二). 将刻度值变为字符串
from matplotlib import pyplot as plt
import random
x = range(0,120)
y = [random.randint(20,40) for i in x]
plt.plot(x,y)
lables_x = ["10h{}m".format(i) for i in range(60)]
lables_x += ["11h{}m".format(i) for i in range(60)]
plt.xticks(list(x)[::10], lables_x[::10], rotation = 45)
# list(x)[::10] 作用是用列表元素将x轴平分
# lables_x[::10]作用是将每个列表元素用字符串代替
# rotation = 45 作用是将字符串逆时针旋转45度
plt.show()
4. 显示描述信息
plt.xlabel("文本1") # 为X轴添加说明信息
plt.ylabel("文本2") # 为Y轴添加说明信息
plt.title("标题文本") # 为图添加标题信息
5. 添加网格线
plt.grid()
plt.grid(alpha = 0.4) # 网格线透明度设置为0.4
6. 一图多曲线
x = range(11,31)
y1 = [i for i in range(20)]
y2 = [i for i in range(20,40)]
plt.plot(x,y1,x,y2)
或者画2次:
x = range(11,31)
y1 = [i for i in range(20)]
y2 = [i for i in range(20,40)]
plt.plot(x,y1)
plt.plot(x,y2)
7. 添加图例
plt.plot(x,y1,label = "文本1")
plt.plot(x,y2,label = "文本2")
plt.legend()
8. 修改曲线特征
(一). 修改颜色
plt.plot(x,y,color="r")
"r" | 红色 |
"g" | 绿色 |
"b" | 蓝色 |
"w" | 白色 |
"c" | 青色 |
"y" | 黄色 |
"k" | 黑色 |
(二). 修改样式
plt.plot(x, y, linestyle = "--")
"--" | 两个减号 | 虚线 |
"-" | 一个减号 | 实线 |
"-." | 一个减号一个英文逗号 | 点横线 |
":" | 英文冒号 | 点虚线 |
"*--" | 一个星号两个减号 | 坐标点为星号,线条为虚线 |
"+-." | 一个加号一个减号一个英文逗号 | 坐标点位加号,线条为点虚线 |
(三). 修改粗细
plt.plot(x, y, linewidth = 5)
(四). 修改透明度
plt.plot(x, y, alpha = 0.4)
(五). 组合使用
plt.plot(x, y, color="b", linestyle = "--", alpha = 0.4)
9. 修改x轴、y轴显示区间
plt.xlim([最小值, 最大值])
plt.ylim([最小值, 最大值])
三. 散点图
plt.scatter(x, y)
from matplotlib import pyplot as plt
import random
x = range(1, 32)
y = [random.random() for i in x]
plt.scatter(x, y)
plt.show()
四. 条形图
1. 竖状条形图
plt.bar(x, y)
(一). 宽度
plt.bar(x, y, width = 0.5)
(二). 颜色
plt.bar(x, y, width = 0.5, color = 'r')
2. 横状条形图
plt.barh(x, y)
(一). 宽度
plt.barh(x, y, height = 0.5)
(二). 颜色
plt.barh(x, y, height = 0.5, color = 'r')
五. 直方图
plt.hist(列表名, 组数)
from matplotlib import pyplot as plt
a = [131, 98, 125, 131, 124, 139, 131, 117, 128, 108]
d = 3
num_bins = (max(a)-min(a))//d
plt.figure(figsize=(20,8),dpi=80)
plt.hist(a, num_bins)
plt.xticks(range(min(a),max(a)+d,d))
plt.grid()
plt.show()