Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make part of a bar plot transparent to unhide the filled region beneath it using matplotlib in Python?

I have a pandas dataframe df which looks as follows:

CSP Min Max
A   107.0   111.0
B   126.0   156.0

df.to_dict() is as follows:

{'Min': {'A': 107.0, 'B': 126.0}, 'Max': {'A': 111.0, 'B': 156.0}}

I want to plot a bar plot for A and B by hiding the part between 0 and Min, and only showing the part between Min and Max. Therefore, I chose to color the Min as white color. The code looks as follows:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

fig, ax = plt.subplots(figsize = (12, 8))

df.plot(kind = "bar",
        stacked = True, color = ["white", "orange"],
        ax = ax)

plt.legend([])

And the resulting plot is as shown:
enter image description here

I also want to plot a colored range between 55 and 148. So I used plt.fill_between() for this purpose.

fig, ax = plt.subplots(figsize = (12, 8))

ax.fill_between(x = [-1, 2],
                y1 = [55, 55],
                y2 = [148, 148],
                color = "gray",
                alpha = 0.15,
                )

plt.legend([])

It looks as follows:
enter image description here

Now I want to combine these two into one single plot. I used the following code:

fig, ax = plt.subplots(figsize = (12, 8))

df.plot(kind = "bar",
        stacked = True, color = ["white", "orange"],
        ax = ax)

ax.fill_between(x = [-1, 2],
                y1 = [55, 55],
                y2 = [148, 148],
                color = "gray",
                alpha = 0.15,
                )

plt.legend([])

The resulting plot is as shown:
enter image description here

The problem is that the white bar is overlapping the gray region which it should not. So, how can I make the bottom part of the bar transparent so that the gray region beneath it is still visible?

>Solution :

You can just plot (no stack) df['Max'] with bottom option using df['Min']:

df['Max'].plot(kind = "bar",
               color="orange",
               ax = ax,
               bottom=df['Min'])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading