多直线绘制
import matplotlib.pyplot as plt
import numpy as np
# 设置2条直线
x = np.linspace(-1, 5, 20)
y1 = x + 1 # 直线 y1
y2 = -x + 3 # 直线 y2
# 分别定义2条直线的属性
plt.plot(x, y1, color="blue", linewidth=1.0, linestyle="-")
plt.plot(x, y2, color="red", linewidth=2.0, linestyle="--")
plt.show()
x = np.linspace(-1, 5, 20)表达的是X的坐标从 -1 一直到 5 ,间隔20个单位(将其分为20份)
设置刻度
我们也可以将x,y在分精确一点,就要使用xticks,yticks;也可以将坐标轴改为自己想表达的:
# 设置横轴刻度
plt.xticks([-1, -0.5, 0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5])
# 设置纵轴刻度
plt.yticks([-2, -1.5, -1, -0.5, 0, 0.5, 1, 2, 3, 4, 5, 6])
设置坐标轴:
# 设置横轴刻度
plt.xticks([-1, -0.5, 0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5],
['A', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm'])
# 设置纵轴刻度
plt.yticks([-2, -1.5, -1, -0.5, 0, 0.5, 1, 2, 3, 4, 5, 6],
['A','b','c','d','e','f','g','h','i','j','k','l'])
添加注释
有时候需要对点进行注释,解释一下什么意思:
就会有2种表达方式:
1: scatter() : 要注意得是,它们的数据类型是列表, ###例如 x 为 [2, 3],y 为 [3, 4],这表示会绘制点(2,3),(3, 4)。因此,x 和 y 长度要一样。
2:annotate :相对于scatter(),前者标记1个或多个点 ,后者更加灵活一点。
直接上代码:
plt.plot(x, y1, color="blue", linewidth=1.0, linestyle="-")
plt.scatter([2,3], [3,4], s=30, color="blue") # 注释点([x],[y],大小,颜色)
plt.plot(x, y2, color="red", linewidth=2.0, linestyle="--")
plt.annotate("(2,1)",
xy=(2.5, 1), # 在(2.5, 1)上做标注
fontsize=15 ,) # 字体大小15
还可以试试文字解释,但是Matplotlib不能使用中文注释:
plt.plot(x, y1, color="blue", linewidth=1.0, linestyle="-")
plt.scatter([2,3], [3,4], s=30, color="blue") # 注释点([x],[y],大小,颜色)
plt.plot(x, y2, color="red", linewidth=2.0, linestyle="--")
plt.annotate("(2,1)",
xy=(2.5, 1), # 在(2.5, 1)上做标注
fontsize=15 ,) # 字体大小15
plt.text(3,0,'good',fontdict={'size': 15, 'color': 'yellow'}) # 在(3,0)添加good
添加图例解释
plt.legend(loc=“best”) ,loc的选择
best 系统自己最佳位置
upper right 右上角
lower right 右下角
upper left 左上角
lower left 左下角
plt.plot(x, y1, color="blue", linewidth=1.0, linestyle="-", label="y1")
plt.plot(x, y2, color="red", linewidth=2.0, linestyle="--", label="y2")
plt.legend(loc="best")