如何使用Python中的Matplotlib在第一个子图的顶部将第二个子图带到第一个子图上?

发布于 2025-01-24 05:31:15 字数 1159 浏览 0 评论 0原文

我有一个dataframe df,看起来如下:

    Min Average Max
Score   30  55  80

df.to_dict如下:

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

我想绘制从min到max开始的条形图,并在标记在酒吧中的形式。 我编写了以下代码:

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)

这将我寄给了我,如图所示:

如观察到的,散点图或水平红线作为标记被蓝色棒隐藏。我想把它带到前面。

我将有关散点图的代码线带到了条形图之前,如下所示:

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)

但是我仍然得到相同的图。如何修改代码以使标记可以在正面?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

枫林﹌晚霞¤ 2025-01-31 05:31:15

在我在单独的虚拟环境(不是基本环境)和启动新终端后运行后,第一个代码对我本身起作用。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文