Home > Software design >  How to stack only selected columns in pandas barh plot
How to stack only selected columns in pandas barh plot

Time:09-29

I am trying to plot a bar chart where I would like to have two bars, one stacked and another one not stacked by the side of the stacked one.

I have the first plot which is a stacked plot:

enter image description here

And another plot, with the same lines and columns:

enter image description here

I want to plot it side by side to the columns of the last plot, and not stack it:

This is a code snippet to replicate my problem:

d = pd.DataFrame({'DC': {'col0': 257334.0,
  'col1': 0.0,
  'col2': 0.0,
  'col3': 186146.0,
  'col4': 0.0,
  'col5': 366431.0,
  'col6': 461.0,
  'col7': 0.0,

  'col8': 0.0},
 'DC - IDC': {'col0': 32665.0,
  'col1': 0.0,
  'col2': 156598.0,
  'col3': 0.0,
  'col4': 176170.0,
  'col5': 0.0,
  'col6': 0.0,
  'col7': 0.0,
  'col8': 0.0},
 'No Address': {'col0': 292442.0,
  'col1': 227.0,
  'col2': 298513.0,
  'col3': 117167.0,
  'col4': 249.0,
  'col5': 747753.0,
  'col6': 271976.0,
  'col7': 9640.0,
  'col8': 211410.0}})




d[['DC', 'DC - IDC']].plot.barh(stacked=True)
d[['No Address']].plot.barh( stacked=False, color='red')

CodePudding user response:

You can achieve this only by using matplotlib.pyplot library. First, you need to import NumPy and matplotlib libraries.

import matplotlib.pyplot as plt
import numpy as np

Then,

plt.figure(figsize=(15,8))
plt.barh(d.index, d['DC'], 0.4, label='DC', align='edge')
plt.barh(d.index, d['DC - IDC'], 0.4, label='DC - IDC', align='edge')
plt.barh(np.arange(len(d.index))-0.4, d['No Address'], 0.4, color='red', label='No Address', align='edge')
plt.legend();

Here is what I did:

  • Increase the figure size (optional)
  • Create a BarContainer for each column
  • Decrease the width of each bar to 0.4 to make them fit
  • Align the left edges of the bars with the y positions
  • Normally all bars now are stacked. To put the red bars to the side you need to subtract each y coordinate by the width of the bars (0.4) np.arange(len(d.index))-0.4
  • Finally, add a legend

It should look like that: enter image description here

CodePudding user response:

Use position parameter to draw 2 columns on the same index:

fig, ax = plt.subplots()
d[['DC', 'DC - IDC']].plot.barh(width=0.4, position=0, stacked=True, ax=ax)
d[['No Address']].plot.barh(width=0.4, position=1, stacked=True, ax=ax, color='red')
plt.show()

barh

  • Related