Home > Blockchain >  How can I bring second sub plot on top of first sub plot using matplotlib in Python?
How can I bring second sub plot on top of first sub plot using matplotlib in Python?

Time:04-29

I have a dataframe df which looks as follows:

    Min Average Max
Score   30  55  80

df.to_dict is as follows:

{'Min': {'Score': 30}, 'Average': {'Score': 55}, 'Max': {'Score': 80}}

I want to plot a bar plot starting from Min to Max, and add the Average in the form of a marker in the bar. I wrote the following code:

fig, ax = plt.subplots()

df["Max"].plot(kind = "bar",
              bottom = df["Min"], ax = ax,
              width = 0.1)

ax.scatter(x = 0,
           y = df["Average"],
           marker = "_",
           s = 10000,
           color = "red")

plt.ylim(0, 120)

This returned me the plot as shown: enter image description here

As observed, the scatter plot or the horizontal red line as marker is hidden by the blue bar. I want to bring it on the front.

I brought the line of code regarding scatter plot before the bar plot as follows:

fig, ax = plt.subplots()

plt.scatter(x = 0,
           y = df["Average"],
           marker = "_",
           s = 10000,
           color = "red")

df["Max"].plot(kind = "bar",
              bottom = df["Min"], ax = ax,
              width = 0.1)

plt.ylim(0, 120)

But I am still getting the same plot. How can I modify the code such that the marker can come on the front?

CodePudding user response:

The first code worked for me itself after I ran it in a separate virtual environment (not base environment) and after starting a fresh terminal. enter image description here

  • Related