1 import matplotlib.pyplot as plt 2 import numpy as np 3 from mpl_toolkits.mplot3d import Axes3D 4 import matplotlib.gridspec as gridspec 5 from matplotlib import animation 6 7 def drawLine(): 8 x=np.linspace(-1,1,50) 9 y = 2 * x + 1 10 #simple demo 11 plt.figure() 12 plt.plot(x,y) 13 plt.show() 14 15 def drawCurveLine(): 16 x=np.linspace(-3,3,50) 17 y1=2*x+1 18 y2=x**2 19 plt.figure(num=3,figsize=(8,5)) 20 plt.plot(x,y1,color='red',linewidth=1.0,linestyle='--') 21 plt.plot(x,y2) 22 plt.show() 23 24 def drawCurveLine02(): 25 x = np.linspace(-3, 3, 50) 26 y1 = 2 * x + 1 27 y2 = x ** 2 28 plt.figure(num=3, figsize=(8, 5)) 29 plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--') 30 plt.plot(x, y2) 31 32 #设置x,y轴坐标范围、坐标轴名称 33 plt.xlim((-1, 2)) 34 plt.ylim((-2, 3)) 35 plt.xlabel('I am x') 36 plt.ylabel('I am y') 37 plt.show() 38 39 def drawCurveLine03(): 40 x = np.linspace(-3, 3, 50) 41 y1 = 2 * x + 1 42 y2 = x ** 2 43 plt.figure(num=3, figsize=(8, 5)) 44 plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--') 45 plt.plot(x, y2) 46 47 plt.xlim((-1, 2)) 48 plt.ylim((-2, 3)) 49 # 设置刻度名称 50 plt.yticks([0,1,2],[r'$really bad$',r'$normal$',r'$good$']) 51 plt.xlabel('I am x') 52 plt.ylabel('I am y') 53 plt.show() 54 55 def drawCurveLine04(): 56 x = np.linspace(-3, 3, 50) 57 y1 = 2 * x + 1 58 y2 = x ** 2 59 plt.figure(num=3, figsize=(8, 5)) 60 plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--') 61 plt.plot(x, y2) 62 63 plt.xlim((-1, 2)) 64 plt.ylim((-2, 3)) 65 plt.yticks([0,1,2],[r'$really bad$',r'$normal$',r'$good$']) 66 67 # 设置边框颜色,默认是白色 68 ax = plt.gca() 69 ax.spines['right'].set_color('green') 70 ax.spines['top'].set_color('green') 71 plt.xlabel('I am x') 72 plt.ylabel('I am y') 73 plt.show() 74 75 def drawCurveLine05(): 76 x = np.linspace(-3, 3, 50) 77 y1 = 2 * x + 1 78 y2 = x ** 2 79 plt.figure(num=3, figsize=(8, 5)) 80 plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--') 81 plt.plot(x, y2) 82 83 plt.xlim((-1, 2)) 84 plt.ylim((-2, 3)) 85 plt.yticks([0,1,2],[r'$really bad$',r'$normal$',r'$good$']) 86 ax = plt.gca() 87 ax.spines['right'].set_color('none') 88 ax.spines['top'].set_color('none') 89 #设置刻度显示位置 90 ax.xaxis.set_ticks_position('bottom') 91 #设置spine-bottom位置 92 ax.spines['bottom'].set_position(('data',0)) 93 ax.spines['left'].set_position(('data', 0)) 94 95 plt.xlabel('I am x') 96 plt.ylabel('I am y') 97 plt.show() 98 99 def drawCurveLine06(): 100 x = np.linspace(-3, 3, 50) 101 y1 = 2 * x + 1 102 y2 = x ** 2 103 plt.figure(num=3, figsize=(8, 5)) 104 plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--',label='linear line') 105 plt.plot(x, y2,label='square line') 106 #显示图例 107 plt.legend(loc='upper right') 108 109 plt.xlabel('x') 110 plt.ylabel('y') 111 plt.show() 112 113 def drawCurveLine07(): 114 x = np.linspace(-3, 3, 50) 115 y1 = 2 * x + 1 116 y2 = x ** 2 117 plt.figure(num=3, figsize=(8, 5)) 118 line1=plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--') 119 line2=plt.plot(x, y2) 120 plt.xlabel('x') 121 plt.ylabel('y') 122 123 #显示图例 124 plt.legend(labels=['up','down'],loc='best') 125 plt.show() 126 127 def drawCurveLine08(): 128 x = np.linspace(-3, 3, 50) 129 y = 2 * x + 1 130 plt.figure(num=3, figsize=(8, 5)) 131 plt.plot(x, y) 132 x0=1 133 y0=2*x0+1 134 plt.plot([x0,x0,],[0,y0,],'k--',linewidth=2.5) 135 #plt.plot([1, 1, ], [0, 3, ], 'k--', linewidth=2.5) 136 #标记点(1,3) 137 plt.scatter([x0,],[y0,],s=50,color='b') 138 #plt.scatter([1, ], [3, ], s=100, color='b') 139 #标注点(1,3) 140 plt.annotate(r'$2x+1=%s$'%y0,xy=(x0,y0),xycoords='data',xytext=(+30,-30), 141 textcoords='offset points',fontsize=16, 142 arrowprops=dict(arrowstyle='->',connectionstyle='arc3,rad=.2')) 143 144 #添加注释text 145 plt.text(-3,3,r'$This is the some text. musigma_ialpha_t$',fontdict={'size':'16','color':'r'}) 146 ax = plt.gca() 147 ax.spines['right'].set_color('none') 148 ax.spines['top'].set_color('none') 149 ax.spines['left'].set_position(('data',0)) 150 ax.spines['bottom'].set_position(('data',0)) 151 plt.show() 152 153 def drawCurveLine09(): 154 x = np.linspace(-3,3,50) 155 y = 0.1*x 156 plt.figure() 157 # 在 plt 2.0.2 或更高的版本中, 设置 zorder 给 plot 在 z 轴方向排序 158 plt.plot(x,y,linewidth=60,zorder=1) 159 160 ax=plt.gca() 161 ax.spines['right'].set_color('none') 162 ax.spines['top'].set_color('none') 163 ax.spines['left'].set_position(('data', 0)) 164 ax.spines['bottom'].set_position(('data', 0)) 165 166 for label in ax.get_xticklabels()+ax.get_yticklabels(): 167 #重新调节字体大小 168 label.set_fontsize(12) 169 #设置目的内容的透明度相关参,facecolor调节 box 前景色,edgecolor 设置边框, 本处设置边框为无,alpha设置透明度 170 label.set_bbox(dict(facecolor='white',edgecolor='None',alpha=0.7,zorder=2)) 171 plt.show() 172 173 #散点图 174 def drawRandomPoint(): 175 n=1024 176 x=np.random.normal(0,1,n) 177 y=np.random.normal(0,1,n) 178 t=np.arctan2(y,x) 179 180 #x,y为位置,s是指size,c为颜色,alpha 为透明度 181 plt.scatter(x,y,s=75,c=t,alpha=.5) 182 plt.xlim(-1.5,1.5) 183 plt.xticks(())#忽略(隐藏) xticks 184 plt.ylim(-1.5,1.5) 185 plt.yticks(())#忽略(隐藏) yticks 186 plt.show() 187 188 def drawBar(): 189 n=12 190 x=np.arange(n) 191 y1=(1-x/float(n))*np.random.uniform(0.5,1.0,n) 192 y2=(1-x/float(n))*np.random.uniform(0.5,1.0,n) 193 194 #画柱状图 195 plt.bar(x,+y1,facecolor='#9999ff',edgecolor='white') 196 plt.bar(x,-y2,facecolor='#ff9999',edgecolor='white') 197 #添加文本 198 for X,Y in zip(x,y1): 199 plt.text(X,Y+0.1,'%.2f'%Y,ha='center',va='top') 200 for X,Y in zip(x,y2): 201 plt.text(X,-Y-0.1,'%.2f'%Y,ha='center',va='bottom') 202 plt.xlim(-5,n) 203 plt.xticks(()) 204 plt.ylim(-1.25,1.25) 205 plt.yticks(()) 206 plt.show() 207 208 def f(x,y): 209 #the height function 210 return (1-x/2+x**5+y**3)*np.exp(-x**2-y**2) 211 #等高线 212 def drawContours(): 213 n=256 214 x=np.linspace(-3,3,n) 215 y=np.linspace(-3,3,n) 216 #在二维平面中将每一个x和每一个y分别对应起来,编织成栅格 217 X,Y=np.meshgrid(x,y) 218 #使用函数plt.contourf把颜色加进去 219 #位置参数分别为:X, Y, f(X,Y),透明度0.75,并将 f(X,Y) 的值对应到color map的暖色组中寻找对应颜色 220 #8代表等高线的密集程度 221 C=plt.contour(X,Y,f(X,Y),8,alpha=.75,cmap=plt.cm.hot) 222 223 #添加高度数字 224 plt.clabel(C,inline=True,fontsize=10) 225 plt.xticks(()) 226 plt.yticks(()) 227 plt.show() 228 229 #矩形图 230 def drawMatrix(): 231 a = np.array([0.313660827978, 0.365348418405, 0.423733120134, 232 0.365348418405, 0.439599930621, 0.525083754405, 233 0.423733120134, 0.525083754405, 0.651536351379]).reshape(3, 3) 234 # imshow 内插法 ,origin='lower'代表的就是选择的原点的位置 235 plt.imshow(a,interpolation='nearest',cmap='bone',origin='lower') 236 #添加一个colorbar,shrink参数,使colorbar的长度变短为原来的92% 237 plt.colorbar(shrink=.92) 238 plt.xticks(()) 239 plt.yticks(()) 240 plt.show() 241 242 def draw3D(): 243 fig = plt.figure() 244 ax = Axes3D(fig) 245 x = np.arange(-4,4,0.25) 246 y = np.arange(-4,4,0.25) 247 #将 X 和 Y 编织成栅格 248 x,y = np.meshgrid(x,y) 249 r = np.sqrt(x**2+y**2) 250 #高 251 z = np.sin(r) 252 #画三维曲面,并将一个 colormap rainbow 填充颜色,之后将三维图像投影到 XY 平面上做一个等高线图 253 #rstride 和 cstride 分别代表 row 和 column 的跨度。 254 ax.plot_surface(x,y,z,rstride=1,cstride=1,cmap=plt.get_cmap('rainbow')) 255 256 #添加投影 257 ax.contour(x,y,z,zdir='z',offset=-1,cmap=plt.get_cmap('rainbow')) 258 plt.show() 259 260 #均匀图中图 261 def drawBySubplot(): 262 plt.figure() 263 #表示将整个图像窗口分为2行2列, 当前位置为1 264 plt.subplot(2,2,1) 265 #在第1个位置创建一个小图. 266 plt.plot([0,1],[0,1]) 267 268 plt.subplot(2,2,2) 269 plt.plot([0,1],[0,2]) 270 271 plt.subplot(2,2,3) 272 plt.plot([0,1],[0,3]) 273 274 plt.subplot(2,2,4) 275 plt.plot([0,1],[0,4]) 276 277 plt.show() 278 279 #不均匀图中图 280 def drawBySubplot02(): 281 plt.figure() 282 plt.subplot(2,1,1) 283 plt.plot([0,1],[0,1]) 284 285 plt.subplot(2,3,4) 286 plt.plot([0,1],[0,2]) 287 288 #235等效于2,3,5 289 plt.subplot(235) 290 plt.plot([0,1],[0,3]) 291 292 plt.subplot(236) 293 plt.plot([0,1],[0,4]) 294 295 plt.show() 296 297 #分格显示 298 def drawBySubplot2grid(): 299 plt.figure() 300 #创建第1个小图, (3,3)表示将整个图像窗口分成3行3列, (0,0)表示从第0行第0列开始作图,colspan=3表示列的跨度为3, rowspan=1表示行的跨度为1. colspan和rowspan缺省, 默认跨度为1 301 ax1 = plt.subplot2grid((3,3),(0,0),colspan=3) 302 #画图 303 ax1.plot([1,2],[1,2]) 304 #设置小图的标题 305 ax1.set_title('ax1_title') 306 307 ax2 = plt.subplot2grid((3,3),(1,0),colspan=2) 308 ax3 = plt.subplot2grid((3,3),(1,2),colspan=2) 309 ax4 = plt.subplot2grid((3,3),(2,0)) 310 ax5 = plt.subplot2grid((3,3),(2,1)) 311 312 ax4.scatter([1,2],[2,2]) 313 ax4.set_xlabel('ax4_x') 314 ax4.set_ylabel('ax4_y') 315 316 plt.show() 317 318 #分格显示02 319 def drawByGridspec(): 320 plt.figure() 321 gs = gridspec.GridSpec(3,3) 322 ax6 = plt.subplot(gs[0,:]) 323 ax7 = plt.subplot(gs[1,:2]) 324 ax8 = plt.subplot(gs[1:,2]) 325 ax9 = plt.subplot(gs[-1,0]) 326 ax10 = plt.subplot(gs[-1,-2]) 327 plt.show() 328 329 #分格显示03 330 def drawBySubplots(): 331 #建立一个2行2列的图像窗口,sharex=True表示共享x轴坐标, sharey=True表示共享y轴坐标. ((ax11, ax12), (ax13, ax14))表示第1行从左至右依次放ax11和ax12, 第2行从左至右依次放ax13和ax14. 332 f,((ax11,ax12),(ax13,ax14))=plt.subplots(2,2,sharex=True,sharey=True) 333 #创建一个散点图. 334 ax11.scatter([1,2],[1,2]) 335 #紧凑显示图像 336 plt.tight_layout() 337 plt.show() 338 339 #图中图 340 def drawPlotInPlot(): 341 fig = plt.figure() 342 x = [1,2,3,4,5,6,7] 343 y = [1,3,4,2,5,8,6] 344 #绘制大图,设置大图左下角的位置以及宽高 345 left,bottom,width,height=0.1,0.1,0.8,0.8 346 ax1 = fig.add_axes([left,bottom,width,height]) 347 #颜色为r(red) 348 ax1.plot(x,y,'r') 349 ax1.set_xlabel('x') 350 ax1.set_ylabel('y') 351 ax1.set_title('title') 352 353 #绘制小图 354 left,bottom,width,height=0.2,0.6,0.25,0.25 355 ax2 = fig.add_axes([left,bottom,width,height]) 356 ax2.plot(y,x,'b') 357 ax2.set_xlabel('x') 358 ax2.set_ylabel('y') 359 ax2.set_title('title inside 1') 360 361 plt.axes([0.6,0.2,0.25,0.25]) 362 plt.plot(y[::-1],x,'g') #对y进行了逆序处理 363 plt.xlabel('x') 364 plt.ylabel('y') 365 plt.title('title inside 2') 366 plt.show() 367 368 #次坐标 369 def multiXandY(): 370 x = np.arange(0,10,0.1) 371 y1 = 0.05*x**2 372 y2 = -1 *y1 373 fig,ax1=plt.subplots() 374 #对ax1调用twinx()方法,生成如同镜面效果后的ax2 375 ax2=ax1.twinx() 376 ax1.plot(x,y1,'g-') #green,solid line 377 ax1.set_xlabel('X data') 378 ax1.set_ylabel('Y1 data',color='g') 379 ax2.plot(x,y2,'b-')#blue 380 ax2.set_ylabel('Y2 data',color='b') 381 plt.show() 382 383 def drawAnimation(): 384 fig, ax = plt.subplots() 385 x = np.arange(0, 2 * np.pi, 0.01) 386 line, = ax.plot(x, np.sin(x)) 387 388 def animateX(i): 389 line.set_ydata(np.sin(x + i / 10.0)) 390 391 def init(): 392 line.set_ydata(np.sin(x)) 393 394 ani = animation.FuncAnimation(fig=fig, 395 func=animateX, 396 frames=100, 397 init_func=init, 398 interval=20, 399 blit=False) 400 plt.show() 401 #ani.save('basic_animation.htm',fps=30,extra_args=['-vcodec','libx264']) 402 403 404 drawAnimation()
代码整理来源:https://morvanzhou.github.io/tutorials/data-manipulation/plt/2-1-basic-usage/
官网教程:https://matplotlib.org/tutorials/index.html
官网API文档:https://matplotlib.org/api/pyplot_summary.html