0

I am trying to plot two bars in one graph and make two y-axes on each side of the graph. I think I plotted two bars on the graph, but the red bars appear to be too tiny. So, I think I need two y-axes to make the red bars visible on the graph Can anyone please help me?

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()

This is what I get so far

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Wu Kris
  • 77
  • 8

1 Answers1

2

You need to use subplots method. Try with this method

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()

You can get output like this

Final plot

Zalak Bhalani
  • 979
  • 7
  • 15