【问题标题】:How to make two y-axis on each side of the graph? [duplicate]如何在图形的每一侧制作两个 y 轴? [复制]
【发布时间】:2021-07-22 11:04:45
【问题描述】:

我正在尝试在一个图中绘制两个条形图,并在图的每一侧制作两个 y 轴。我想我在图表上绘制了两个条,但红色条似乎太小了。所以,我想我需要两个 y 轴才能使红色条在图表上可见 谁能帮帮我?

df1 = pd.DataFrame({'hour': ['13', '20', '14', '06', '07', '19', '08', '04', '11', '18', '15', '09',
       '03', '12', '16', '17', '21', '05', '01', '10', '23', '22', '02', '00'],
             'frequency': [941, 504, 297, 224, 170, 145,  97,  92,  92,  90,  79,  79,  78,
        77,  75,  74,  67,  64,  56,  51,  41,  40,  39,  22]})

df2 = pd.DataFrame({'hour':['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11',
       '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23'],
              'amount ($)': [   3517.91,    4328.36,   11683.2 ,    4973.2 ,    7689.22,
          7004.38,    5240.92,  181419.03,   11950.57,   15782.43,
          3368.34, 1626843.81,   34283.42,   39408.19,   48561.55,
         19537.79,   83662.73,   33069.95,  338409.78,  366869.01,
         16106.79,    9890.  ,  325842.28,  485154.98]})
import numpy as np
import matplotlib.pyplot as plt

width = 0.4
x_axis = np.arange(len(df2.index))

frequency = df1['frequency']
amount = df2['amount ($)']

plt.bar(x_axis - width/2, frequency, width, label = 'Frequency', color = 'red')
plt.bar(x_axis + width/2, amount, width, label = 'Amount', color = 'blue')

plt.xticks(x_axis, df2.index, rotation = 90)
plt.show()

【问题讨论】:

    标签: python pandas matplotlib


    【解决方案1】:

    您需要使用subplots 方法。试试这个方法

    import numpy as np
    import matplotlib.pyplot as plt
    
    width = 0.4
    x_axis = np.arange(len(df2.index))
    
    frequency = df1['frequency']
    amount = df2['amount ($)']
    
    fig, ax1 = plt.subplots()
    color = 'red'
    ax1.set_xlabel('Time (hour)')
    ax1.set_ylabel('Frequency', color=color)
    
    ax1.tick_params(axis='y', labelcolor=color)
    ax1.bar(x_axis - width/2, frequency, width, label = 'Frequency', color = 'red')
    ax1.tick_params(axis='x', rotation=90)
    ax2 = ax1.twinx()  # instantiate a second axes that shares the same x-axis
    
    color = 'blue'
    ax2.set_ylabel('Amount', color=color)  # we already handled the x-label with ax1
    ax2.bar(x_axis + width/2, amount, width, label = 'Amount', color = 'blue')
    ax2.tick_params(axis='y', labelcolor=color)
    
    fig.tight_layout()  # otherwise the right y-label is slightly clipped
    plt.show()
    

    你可以得到这样的输出

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-19
      • 1970-01-01
      • 1970-01-01
      • 2022-06-22
      • 1970-01-01
      相关资源
      最近更新 更多