参考matplotlib官方指南:
https://matplotlib.org/tutorials/introductory/pyplot.html#sphx-glr-tutorials-introductory-pyplot-py
pyplot是常用的画图模块,功能非常强大,下面就来见识下它的能力吧
1.快速画出常见图形
import matplotlib.ptplot as plt import numpy as np #x = np.arange(10) x = np.linspace(0,2,100) plt.plot(x,x,label = 'liner') plt.plot(x,x**2,label = 'quadratic') plt.plot(x,x**3,label = 'cubic') plt.xlabel('x label') plt.ylabel('y label') plt.title('Simple Plot') plt.legend() plt.show()
import matplotlib.pyplot as plt import numpy as np x = np.arange(0,10,0.2) y = np.cos(x) fig =plt.figure() ax = fig.add_subplot(111) ax.plot(x,y) plt.show() import matplotlib.pyplot as plt import numpy as np x = np.arange(0,10,0.2) y = np.cos(x) fig =plt.figure() ax2 = fig.add_subplot(2,2,2) ax2.plot(x,y) plt.show()
import matplotlib.pyplot as plt import numpy as np t = np.arange(0,5,0.2) plt.plot(t,t,'r_',t,t**2,'bs',t,t**3,'g^') plt.show()
2.使用关键字字符串作图
import matplotlib.pyplot as plt import numpy as np data = { 'a':np.arange(50), 'c':np.random.randint(0,50,50), 'd':np.random.randn(50) } data['b'] = data['a'] + 10*np.random.randn(50) data['d'] = np.abs(data['d'])*100 # x坐标 数组a,y坐标 数组b,颜色c 数组c 大小s数组d plt.scatter('a','b',c = 'c',s = 'd',data= data) plt.xlabel('entry a') plt.ylabel('entry b') plt.show()
3.使用类变量画图
import matplotlib.pyplot as plt import numpy as np names = [1,2,3] values = [1,10,100] # 设置画布大小 plt.figure(1,figsize = (9,3)) # 画出三幅图,分别设置 plt.subplot(1,3,1) plt.bar(names,values) plt.subplot(1,3,2) plt.scatter(names,values) plt.subplot(1,3,3) plt.plot(names,values) plt.suptitle('Categorical Plotting') plt.show()
4.创建多图
import matplotlib .pyplot as plt plt.figure(1) plt.subplot(2,1,1) plt.plot([1,2,3]) plt.title('Easy as 1,2,3') plt.subplot(2,1,2) plt.plot([4,5,6]) plt.show() plt.figure(2) plt.plot([4,5,6]) plt.show()
import matplotlib.pyplot as plt import numpy as np np.random.seed(19680801) data = np.random.randn(2,100) fig,axs = plt.subplots(2,2,figsize = (5,5)) axs[0,0].hist(data[0]) axs[1,0].scatter(data[0],data[1]) axs[0,1].plot(data[0],data[1]) axs[1,1].hist2d(data[0],data[1]) plt.show()
5.添加文本:轴标签,属性标签
import matplotlib.pyplot as plt
import numpy as np
mu ,sigma = 100,15 x = mu + sigma *np.random.randn(100000) n,bins, patches = plt.hist(x,50,normed = True ,facecolor = 'g',alpha = 0.75) plt.xlabel('Smarts') plt.ylabel('Probability') plt.title('Histogram of IQ') # 支持latex/ plt.text(60,0.025,r'$mu =100, sigma = 15$') plt.axis([40,160,0,0.03]) plt.grid(True) plt.show()