作为python的小白我,在学习过程中,将绘图常规操作记在博客上,方便日后使用。参考书籍:深度学习之pytorch实战计算机视觉,唐进民,如若侵权,本人立马删除
在实际应用中,我们习惯将 import matplotlib 写成 import matplotlib.pyplot as plt
1 线型图
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(42)
x = np.random.randn(30)
plt.plot(x, "r--o")
plt.show()#我的pycharm显示不出图,加了show就可以了
1 这里通过设置随机种子,保证结果复现,防止每次随机后不一样。
2 所产生的30点通过plt.plot()函数用线条连接。
3 r–o类似matlab 用来确定线形颜色等
2 标签和图例
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(42)
x = np.random.randn(30)
y = np.random.randn(30)
x,= plt.plot(x, "r--o")
y,= plt.plot(y,"b-*")
plt.title("example")
plt.xlabel("x")
plt.ylabel("y")
plt.legend([x,y],["x","y"])
plt.show()
同matlab,这里不多说了。
3 子图
一张图显示多个图像,用到的函数是Subplot
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(42)
a = np.random.randn(30)
b = np.random.randn(30)
c = np.random.randn(30)
d = np.random.randn(30)
fig = plt.figure()
ax1 = fig.add_subplot(2,2,1)
ax2 = fig.add_subplot(2,2,2)
ax3 = fig.add_subplot(2,2,3)
ax4 = fig.add_subplot(2,2,4)
A, = ax1.plot(a,"r--o")
ax1.legend([A],["A"])
B, = ax2.plot(b,"r-o")
ax1.legend([B],["B"])
C, = ax3.plot(c,"r--o")
ax1.legend([C],["C"])
D, = ax4.plot(d,"r--o")
ax1.legend([D],["D"])
plt.show()
在绘制子图时,先需要通过 fig=plt.figure() 定义一个实例,然后通过 fig.add_subplot()添加子图
4 散点图
np.random.seed(42)
a = np.random.randn(30)
b = np.random.randn(30)
plt.scatter(a,b,c="g",marker="o",label="A,B")
plt.xlabel("a")
plt.ylabel("b")
plt.legend(loc=1)
plt.show()
其中,"c"指定绘制点时使用哪种颜色,g表示绿色。marker指定绘制点的形状,o表示圆形。label指定绘制点使用的图例,还可以通过plt.legend()对图例位置强制设定。如下: