matplotlib summary (compare Basic Edition)

1. Basic

  • Import library
    import matplotlib.pyplot as plt
  • Draw a straight line
    plt.plot (x, y)
  • Figure showing
    plt.show ()
  • FIG create a
    plt.figure (num = 3, figsize = (8, 5),)
  • Color display line style, thickness
    plt.plot (x, y1, color = 'red', linewidth = 1.0, linestyle = '-')
  • Set in the range
    plt.xlim ((- 1,2))
    plt.ylim ((- 1,2))
  • Set coordinate axis name
    plt.xlabel ( 'L AM X')
    plt.ylabel ( 'L AM Y')
  • Indexing axes disposed
    plt.yticks ([- 2, -1.8, -1, 1.22,. 3],
            [R & lt 'Really $ \ $ Bad', R & lt '$ $ Bad', R & lt 'Normal $ $', R & lt '$ Good $', r 'Really $ \ $ Good'])
    !!! If you do not want to get rid of Latex format $ both sides, and the beginning of the r
  • Provided the position of the axis
# gca = 'get current axis' 得到当前的坐标轴
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')

#[ 'top' | 'bottom' | 'both' | 'default' | 'none' ]
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
ax.spines['bottom'].set_position(('data', 0))
ax.spines['left'].set_position(('data',0))
  • 设置图例
    plt.plot(x, y1, label=‘linear line’)
    plt.plot(x, y2, color=‘red’, linewidth=1.0, linestyle=’–’, label=‘square line’)
    plt.legend(loc=‘upper right’)
    ### 高阶图例用法
    l1, = plt.plot(x, y1, label=‘linear line’)
    l2, = plt.plot(x, y2, color=‘red’, linewidth=1.0, linestyle=’–’, label=‘square line’)
    plt.legend(handles=[l1, l2], labels=[‘up’, ‘down’], loc=‘best’)

general

  • Scatter
    plt.scatter (x, y, s = 50, color = 'r')
  • Column Chart
plt.bar(X, +Y1, facecolor='#9999ff', edgecolor='white')
# 给每个柱形上面加数字
for x, y in zip(X, Y1):
    # ha: 横向对齐,用哪个点
    # va: 纵向对齐,用那个点
    plt.text(x + 0.4, y + 0.05, '%.2f' % y, ha='center', va='bottom')
  • Contour FIG.
import matplotlib.pyplot as plt
import numpy as np

def f(x,y):
    # the height function
    return (1 - x / 2 + x**5 + y**3) * np.exp(-x**2 -y**2)

n = 256
x = np.linspace(-3, 3, n)
y = np.linspace(-3, 3, n)
# 初始化网格
X,Y = np.meshgrid(x, y)
# 画颜色   分成x+2份(这是8+2份) alpha 透明度  cmap映射表 
plt.contourf(X, Y, f(X, Y), 8, alpha=.75, cmap=plt.cm.hot)

# 画边缘 
C = plt.contour(X, Y, f(X, Y), 8, colors='black', linewidth=.5)
# 画标签    inlie 不画在线里面
plt.clabel(C, inline=True, fontsize=10)

plt.xticks(())
plt.yticks(())
plt.show()

Here Insert Picture Description

  • Show pictures imshow
# a是每个像素的大小  interploation风格  
plt.imshow(a, interpolation='nearest', cmap='bone')
# shrink是缩短情况
plt.colorbar(shrink=.92)

# 去掉 坐标轴
plt.xticks(())
plt.yticks(())
  • 3D pictures
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

# 初始化模板
fig = plt.figure()
# 将模板换成3D模板
ax = Axes3D(fig)

x= np.arange(-4,4,0.25)
y= np.arange(-4,4,0.25)
x,y = np.meshgrid(x,y)

r = np.sqrt(x**2+y**2)
z = np.cos(r)

# !!!画3D图
# rstride,cstride ---> 跨度     edgecolor 边缘颜色
ax.plot_surface(x,y,z,rstride=1,cstride=1,cmap=plt.get_cmap('rainbow'),edgecolor='black')
# 画3D的投影图   zdir 投影到那个轴  offset 偏移量
ax.contourf(x,y,z,zdir='z',offset=-2,cmap='rainbow')

ax.set_zlim(-2,2)

plt.show()

3D pictures

  • Add comments
    explain parameter 1: Text, 2: arrow pointing coordinates, 3: 4 according to the rules: Text offset 5: at regular
    fontSize: text size, arrowprops: dictionary pointer, arrowstyle: arrow style, connectionstyle: arrow style
plt.annotate(r'\$2x+1=%s\$' % y0, xy=(x0, y0), xycoords='data', xytext=(+30, -30),
             textcoords='offset points', fontsize=16,
             arrowprops=dict(arrowstyle='->', connectionstyle="arc3,rad=.2"))

1: coordinates, 2: Text 3: Text Dictionary

plt.text(-3.7, 3, r'\$This\ is\ the\ some\ text. \mu\ \sigma_i\ \alpha_t\$',
         fontdict={'size': 16, 'color': 'r'})
  • Set axis scale text attributes
for label in ax.get_xticklabels() + ax.get_yticklabels():
	# 字体大小
    label.set_fontsize(12)
    # facecolor 前景色,edgecolor 边缘,alpha 透明度  ,zorder=2 规则
    label.set_bbox(dict(facecolor='white', edgecolor='none', alpha=0.8, zorder=2))

In the upper

  • subplot in-one display
import matplotlib.pyplot as plt

plt.figure()
plt.subplot(2,1,1)
plt.plot([0,1],[0,1])

plt.subplot(2,3,4)
plt.plot([0,1],[0,1])

plt.subplot(2,3,5)
plt.plot([0,1],[0,1])

plt.subplot(2,3,6)
plt.plot([0,1],[0,1])

plt.show()

In-one

  • My favorite one-one
# 导入包
import matplotlib.gridspec as gridspec
import matplotlib.pyplot as plt
plt.figure()
gs = gridspec.GridSpec(3,3)
ax1 = plt.subplot(gs[0,:])
ax2 = plt.subplot(gs[1,:2])
ax3 = plt.subplot(gs[1:,2])
ax4 = plt.subplot(gs[2,0])
ax5 = plt.subplot(gs[2,1])
plt.show()
  • GIF
import matplotlib.pyplot as plt
from matplotlib import animation
import numpy as np

fig, ax=plt.subplots()

x = np.arange(0,2*np.pi,0.01)
line, = ax.plot(x,np.sin(x))

def animate(i):
    line.set_ydata(np.sin(x+i/30))
    return line,

def init():
    line.set_ydata(np.sin(x))
    return line,

#!!! 必须要有 ani =  fig:图片,func:动作的函数,frames:帧数,inin_func:初始时候, interval:隔多长更新一下
ani = animation.FuncAnimation(fig=fig,func=animate,frames=100,init_func=init,interval=20,blit=False)
# 保存我们的动图
ani.save('1.gif',writer='imagemagick')
plt.show()

Published 31 original articles · won praise 13 · views 9900

Guess you like

Origin blog.csdn.net/qq_43497702/article/details/98485185