Home > Software engineering >  How to fill or shade area between two corresponding points in stacked bar plots in Python using matp
How to fill or shade area between two corresponding points in stacked bar plots in Python using matp

Time:12-14

I have a dataframe df which looks as follows:

A   B
X   5   7
Y   10  5

df.to_dict() gives the following:

{'A': {'X': 5, 'Y': 10}, 'B': {'X': 7, 'Y': 5}}

I have created a stacked bar plot using

df.plot(kind = "bar", stacked = True)

It look as follows: enter image description here

I want to shade the region between A in X and Y bar, and the same for B. The shaded region reflect how the value of A and B has changed between X and Y. It should look something as shown: enter image description here

How can I fill areas in between these two stacked bar plots using matplotlib in Python keeping the original structure of bar plot intact?

CodePudding user response:

Here's another fill_between with more general approach:

# loop through the bars to get the bottom and top points
bottoms = []
tops = []
for patch in ax.patches:
    x,y = patch.get_xy()
    w,h = patch.get_width(), patch.get_height()
    
    bottoms  = [(x,y), (x w, y)]
    tops  = [(x, y h), (x w, y h)]

# convert to numpy for easy slicing
tops = np.array(tops)
bottoms = np.array(bottoms)

# extract the x coordinates
x = np.unique(bottoms[:,0])
num_x = len(x)

# fill between each bottom and top pairs
for i in range(0, len(bottoms), num_x):
    plt.fill_between(x, tops[i:i num_x, 1], bottoms[i:i num_x, 1], alpha=0.5)

Output:

enter image description here

CodePudding user response:

Here is a way using enter image description here

  • Related