Home > Mobile >  stacked bartplot and line on the same chart
stacked bartplot and line on the same chart

Time:10-28

Consider the following example:

import pandas as pd
import matplotlib.pyplot as plt

dfa = pd.DataFrame({'time' : [pd.to_datetime('2021-01-01'),
                             pd.to_datetime('2021-01-01'),
                             pd.to_datetime('2021-01-02'),
                             pd.to_datetime('2021-01-02'),
                             pd.to_datetime('2021-01-03'),
                             pd.to_datetime('2021-01-03'),
                             ],
                   'group' : ['a','b','a','b','a','b'],
                   'value' : [1,2,3,2,5,5]})

dfa
Out[266]: 
        time group  value
0 2021-01-01  a     1    
1 2021-01-01  b     2    
2 2021-01-02  a     3    
3 2021-01-02  b     2    
4 2021-01-03  a     5    
5 2021-01-03  b     5  

dli = pd.DataFrame({'time' :[pd.to_datetime('2021-01-01'),
                             pd.to_datetime('2021-01-02'),
                             pd.to_datetime('2021-01-03')],
                    'value' : [100,200,50]})

dli
Out[267]: 
        time  value
0 2021-01-01  100  
1 2021-01-02  200  
2 2021-01-03  50   

I am trying to create a stacked bar chart using dfa with plot a line chart on top of it using dli. The issue is that my code below makes the bar plot disappear (although the charts plotted individually work).

fig, ax1 = plt.subplots(figsize=(12, 4))
ax2 = ax1.twinx()

dfa.set_index(['time','group']).unstack().plot.bar(stacked = True, ax = ax1)
dli.set_index('time').plot(ax = ax2, color = 'red',
                           linewidth = 4, secondary_y = True)

enter image description here

Can you see what the issue is? For instance, the single line works

dfa.set_index(['time','group']).unstack().plot.bar(stacked = True)

enter image description here

Thanks!

CodePudding user response:

Try:

# plot data
d = dfa.set_index(['time','group']).unstack().cumsum(1)

fig,ax = plt.subplots()
for c in d.columns[::-1]:
    ax.bar(d.index, d[c], label=c)
ax.legend()

ax1 = ax.twinx()

ax1.plot(dli['time'], dli['value'], color='r', label='value')
ax1.legend(loc='upper right')

Output:

enter image description here

  • Related