pythonmatplotlib 中的 axes用法

    科技2024-06-12  67

    import pandas as pd import numpy as np import matplotlib.pyplot as plt a = pd.DataFrame(np.arange(30).reshape((5, 6)), columns=list('abcdef'),index=['a1','a2','a3','a4','a5']) n = 1 # n = 2 # axes 没有固定的类型,如果n 只有一位,那么axes就是完全的一个普通的数字 # 如果n>1 且 plt.subplots(n, 1) 中括号里边的数字是1 那么就是一个一维数组,那么引用的时候,就应该ax=ax[i] # 如果n>1 且 plt.subplots(n, 2) 中括号里边的数字是2 或者是大于2的数字,那么就是一个二维数组,引用的时候,应该ax=ax[1][1] 类型这样 fig1, axes = plt.subplots(n,1,figsize=(15, 10)) print(axes) # AxesSubplot(0.125,0.11;0.775x0.77) # 当 n = 1时 # # [<matplotlib.axes._subplots.AxesSubplot object at 0x0000000EEB5B13C8> # <matplotlib.axes._subplots.AxesSubplot object at 0x0000000EEF03A898> # <matplotlib.axes._subplots.AxesSubplot object at 0x0000000EEF06EE48> # <matplotlib.axes._subplots.AxesSubplot object at 0x0000000EEF0AB438> # <matplotlib.axes._subplots.AxesSubplot object at 0x0000000EEF0DC9E8> # <matplotlib.axes._subplots.AxesSubplot object at 0x0000000EEF10EF98>] # print(type(axes)) # <class 'matplotlib.axes._subplots.AxesSubplot'> # 当 n =1 时 # <class 'numpy.ndarray'> x = 0 for i in range(n): # if n == 1: # a.plot(marker='h', markersize=6, linewidth=2.0, linestyle='-', ax=axes) # else: # a.plot(marker='h', markersize=6, linewidth=2.0, linestyle='-', ax=axes[x]) a.plot(marker='h', markersize=6, linewidth=2.0, linestyle='-', ax=axes[x] if n > 1 else axes) # 由于axes 的特殊性 # 所以 现在用一个三目运算符替代一下 x += 1 plt.legend(loc='best',labels=list(a.columns.values)) plt.show()
    Processed: 0.013, SQL: 9