pandas stacked bar plot - change the edgecolor of stacked bar

Viewed 1070

Can I get the edge settings to apply on all stacked bar as one?

here is an example:

df = pd.DataFrame([[2,5,7,11], [4,8,11,45]]).T
ax = df.plot.bar(stacked=True)
ax.containers[0][2].set_edgecolor('green')
ax.containers[0][2].set_linewidth(5)
ax.containers[1][2].set_edgecolor('green')
ax.containers[1][2].set_linewidth(5)

this gives: enter image description here

what I want is the green edge to be around the whole bar without breaking between the stacked rectangles, any ideas?

2 Answers

I'm not sure you can specify to not plot one of the edges for each of the Rectangle. So one idea is to plot a Rectangle independently and access the positions, height and width from the ax.containers.

from matplotlib.patches import Rectangle
df = pd.DataFrame([[2,5,7,11], [4,8,11,45]]).T
ax = df.plot.bar(stacked=True)
ax.add_patch(Rectangle(xy=ax.containers[0][2].get_xy(), 
                       width=ax.containers[0][2].get_width(),
                       height=ax.containers[0][2].get_height() 
                              +ax.containers[1][2].get_height(), 
                       fc='none', ec='green', linewidth=5)
            )

enter image description here

You can draw it in two steps: first the stacked bars and then the summed bars.

from matplotlib import pyplot as plt
import numpy as np
import pandas as pd

df = pd.DataFrame([[2, 5, 7, 11], [4, 8, 11, 45]]).T
ax = df.plot.bar(stacked=True)
ax = df.sum(axis=1).plot.bar(facecolor='none', edgecolor='green', lw=5, ax=ax)

example plot

To only draw a rectangle around some bars, set the sum to NaN except for the bars to be highlighted:

from matplotlib import pyplot as plt
import numpy as np
import pandas as pd

df = pd.DataFrame([[2, 5, 7, 11], [4, 8, 11, 45]]).T
dfs = df.sum(axis=1)
dfs.iloc[df.index != 2] = np.nan

ax = df.plot.bar(stacked=True)
ax = dfs.plot.bar(facecolor='none', edgecolor='green', lw=5, ax=ax)

only a rectangle around bar 2

Related