创建

    1. # an empty figure with no Axes
    2. fig = plt.figure()
    3. # a figure with a single Axes
    4. fig, ax = plt.subplots()
    5. # a figure with a 2x2 grid of Axes
    6. fig, axs = plt.subplots(2, 2)

    坐标轴

    1. # 坐标轴名称
    2. ax.xlabel("横坐标")
    3. ax.ylabel("纵坐标")
    4. # 坐标范围
    5. ax.xlim((-1,2))
    6. ax.ylim((-1,2))
    7. # 刻度&自定义刻度
    8. ax.xticks(np.linspace(-1,2,5)
    9. ax.yticks([0,30,60,90],['zero',30,'sixty',90])
    10. # 坐标轴颜色
    11. # 位置:left,right,top,bottom
    12. # 颜色:none为无颜色
    13. ax.spines['left'].set_color('none')
    14. # 选取X,Y坐标轴
    15. ax.xaxis.set_ticks_position("top") #bottom
    16. ax.yaxis.set_ticks_position("right") #left
    17. # 移动坐标轴
    18. ax.spines['bottom'].set_position(('data',0))
    19. ax.spines['bottom'].set_position(('data',0))
    20. # 坐标轴放缩
    21. ax.set_yscale('log')

    图例(legend)

    1. fig, ax = plt.subplots()
    2. x = np.arange(0, 10, 1)
    3. l1, = ax.plot(x, 2 * x, label='up')
    4. l2, = ax.plot(x, 3 * x, color='red', linewidth=1.0, linestyle='--', label='down')
    5. # 默认图例
    6. ax.legend()
    7. # 手动图例
    8. ax.legend(handles=[l1, l2, ], labels=['$y=x^2$','bbb'],loc="best")
    9. fig.show()

    注解(annotation)
    image.png

    1. import matplotlib.pyplot as plt
    2. import numpy as np
    3. x = np.linspace(0, 10, 50)
    4. y = 2 * x + 1
    5. fig, ax = plt.subplots()
    6. ax.plot(x, y)
    7. x0 = 4
    8. y0 = 2 * x0 + 1
    9. ax.scatter(x0, 0, s=50, color='b')
    10. ax.plot([x0, x0], [0, y0], 'k--', lw=2.5)
    11. # 注解 箭头
    12. ax.annotate(r"$2x+1=%s$" % y0,
    13. xy=(x0, y0), xycoords='data',
    14. xytext=(+30, -30), textcoords='offset points',
    15. fontsize=16,
    16. arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=.2')
    17. )
    18. # 打字
    19. ax.text(-3.7, 3,
    20. r"$This\ is\ the\ some\ text. \ \mu\ \sigma_i\ \alpha_t$",
    21. fontdict={'size': 16, 'color': 'r'}
    22. )

    tick透明度设置
    如下图,坐标轴的刻度影响了线条的绘制效果,可以通过将坐标轴刻度进行虚化显示出更好的效果。
    image.png

    1. import matplotlib.pyplot as plt
    2. import numpy as np
    3. x = np.linspace(-3, 3, 50)
    4. y = 0.1 * x
    5. fig, ax = plt.subplots()
    6. ax.plot(x, y, lw=10)
    7. ax.spines['top'].set_color('none')
    8. ax.spines['right'].set_color('none')
    9. ax.spines['bottom'].set_position(('data', 0))
    10. ax.spines['left'].set_position(('data', 0))
    11. # 设置层叠优先次序 数值大的在上层
    12. ax.set_zorder(2)
    13. # 循环处理
    14. for tick in ax.get_xticklabels() + ax.get_yticklabels():
    15. # 改变刻度字体大小
    16. tick.set_fontsize(12)
    17. tick.set_zorder(1)
    18. # 改变刻度bounding box的样式
    19. tick.set_bbox(dict(facecolor='white', edgecolor="None", alpha=0.7))

    散点图 scatter
    image.png

    1. import matplotlib.pyplot as plt
    2. import numpy as np
    3. n = 1024
    4. X = np.random.normal(0, 1, n)
    5. Y = np.random.normal(0, 1, n)
    6. T = np.arctan2(Y, X)
    7. # s:size c:color alpha:透明度
    8. plt.scatter(X, Y, s=75, c=T, alpha=0.5)
    9. plt.xlim((-1.5, 1.5))
    10. plt.ylim((-1.5, 1.5))
    11. plt.xticks(())
    12. plt.yticks(())
    13. plt.show()

    条形图 bar
    image.png

    1. import matplotlib.pyplot as plt
    2. import numpy as np
    3. %matplotlib inline
    4. n = 12
    5. X = np.arange(n)
    6. Y = (1 - X / n) * np.random.uniform(0.5, 1.0, n)
    7. fig, ax = plt.subplots()
    8. ax.bar(X, Y, facecolor='#9999ff', edgecolor='white')
    9. ax.bar(X, -Y, facecolor='#ff9999', edgecolor='white')
    10. # 设置坐标轴和标签
    11. ax.set_xlim(-.5, n)
    12. ax.set_ylim(-1.25, 1.25)
    13. ax.set_xticks(())
    14. ax.set_yticks(())
    15. # 注解
    16. for x, y, y_hat in zip(X, Y, -Y):
    17. # ha: horizontal alignment va:vertical alignment
    18. ax.text(x, y + 0.05, '%.2f' % y, ha='center', va='bottom')
    19. ax.text(x, y_hat - 0.15, '%.2f' % y_hat, ha='center', va='bottom')
    20. fig.show()

    等高线图 contours
    image.png

    1. import matplotlib.pyplot as plt
    2. import numpy as np
    3. # 伪数据生成
    4. def gen_data(x, y):
    5. return (1 - x / 2 + x ** 5 + y ** 3) * np.exp(-x ** 2 - y ** 2)
    6. n = 256
    7. x = np.linspace(-3, 3, n)
    8. y = np.linspace(-3, 3, n)
    9. X, Y = np.meshgrid(x, y)
    10. Z = gen_data(X, Y)
    11. # contour and contourf draw contour lines and filled contours, respectively
    12. fig, ax = plt.subplots()
    13. #
    14. ax.contourf(X, Y, Z, levels=8, alpha=0.75, cmap=plt.cm.hot)
    15. C = ax.contour(X, Y, Z, levels=8, colors='black', linewidths=.5)
    16. ax.clabel(C, inline=True, fontsize=10)
    17. ax.set_xticks(())
    18. ax.set_yticks(())
    19. fig.show()

    热力图
    image.png

    1. import matplotlib.pyplot as plt
    2. import numpy as np
    3. import matplotlib
    4. a = np.random.random((3, 3))
    5. fig, ax = plt.subplots()
    6. image = ax.imshow(a, interpolation='nearest', cmap='bone', origin='lower')
    7. fig.colorbar(image, shrink=0.9)
    8. fig.show()

    子图(组图)
    image.png

    1. import matplotlib.pyplot as plt
    2. plt.subplot(2, 1, 1)
    3. plt.plot([0, 1], [0, 1])
    4. plt.subplot(2, 3, 4)
    5. plt.plot([0, 1], [0, 1])
    6. plt.subplot(2, 3, 5)
    7. plt.plot([0, 1], [0, 1])
    8. plt.subplot(2, 3, 6)
    9. plt.plot([0, 1], [0, 1])

    组图
    image.png

    1. import matplotlib.pyplot as plt
    2. import numpy as np
    3. plt.figure()
    4. ax1 = plt.subplot2grid((3, 3), (0, 0), colspan=3, rowspan=1)
    5. ax1.plot([1, 2], [1, 2])
    6. ax2 = plt.subplot2grid((3, 3), (1, 0), colspan=2)
    7. ax3 = plt.subplot2grid((3, 3), (1, 2), rowspan=2)
    8. ax4 = plt.subplot2grid((3, 3), (2, 0))
    9. ax4 = plt.subplot2grid((3, 3), (2, 1))
    10. plt.show()

    图嵌套(绝对定位)
    image.png

    1. import matplotlib.pyplot as plt
    2. fig = plt.figure()
    3. x = np.arange(1, 8)
    4. y = np.arange(1, 8)
    5. left, bottom, width, height = 0.1, 0.1, 0.8, 0.8
    6. ax1 = fig.add_axes([left, bottom, width, height])
    7. ax1.plot(x, y, 'r')
    8. left, bottom, width, height = 0.2, 0.6, 0.25, 0.25
    9. ax2 = fig.add_axes([left, bottom, width, height])
    10. ax2.plot(x, y, 'b')

    双坐标轴
    image.png

    1. x = np.arange(0, 10, 0.1)
    2. y1 = 0.05 * x ** 2
    3. y2 = -1 * y1
    4. fig, ax1 = plt.subplots()
    5. ax2 = ax1.twinx()
    6. ax1.plot(x, y1, 'g--')
    7. ax2.plot(x, y2, 'b--')
    8. ax1.set_xlabel('X data')
    9. ax1.set_ylabel('Y1', color='g')
    10. ax2.set_ylabel('Y2', color='b')