Python 如何在图形的每一侧制作两个y轴?
我试图在一个图形中绘制两个条形图,并在图形的每一侧绘制两个y轴。我想我在图表上画了两条线,但是红色的线看起来太小了。所以,我想我需要两个y轴来使红色条在图形上可见 有人能帮我吗Python 如何在图形的每一侧制作两个y轴?,python,pandas,matplotlib,Python,Pandas,Matplotlib,我试图在一个图形中绘制两个条形图,并在图形的每一侧绘制两个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',
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 ($)']
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()
您可以得到这样的输出
您需要使用
子批次
方法。试试这个方法
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()
您可以得到这样的输出