如何防止pyplot.errorbar导致seaborn barplot的x轴位移

huangapple go评论72阅读模式
英文:

How to prevent pyplot.errorbar from shifting x-axis of seaborn barplot

问题

我想使用Seaborn的barplot绘制数据;我只有均值和标准差。我使用pyplot.errorbar将误差条添加到我的图中,但是它使我的x轴稍微偏移(请参见图中的红色星号)。如何防止这种情况发生?

图表:
如何防止pyplot.errorbar导致seaborn barplot的x轴位移

复制代码:

import seaborn as sn
import matplotlib.pyplot as plt 

### 加载示例数据 ###
health = sns.load_dataset('healthexp')

health_summary = health.groupby(['Country']).Life_Expectancy.agg({'mean','std'}).reset_index()

### 不带误差条的barplot ###
p = sn.barplot(health_summary, x = 'Country', y = 'mean', errorbar=None)

plt.show()

### 带误差条的barplot ###
p = sn.barplot(health_summary, x = 'Country', y = 'mean', errorbar=None)

p.errorbar(x=health_summary['Country'], y=health_summary['mean'], yerr=health_summary['std'], fmt="none", c="k")

plt.show()
英文:

I want to plot data using Seaborn barplot; I only have the mean and standard deviation. I use pyplot.errorbar to add error bars to my plot, however, it shifts my x axis slightly (see red star below in plot). How do I prevent this from happening?

Plots:
如何防止pyplot.errorbar导致seaborn barplot的x轴位移

Code to reproduce:

import seaborn as sn
import matplotlib.pyplot as plt 

### loading example data ###
health = sns.load_dataset('healthexp')

health_summary = health.groupby(['Country']).Life_Expectancy.agg({'mean','std'}).reset_index()


### barplot without errorbars ###
p = sn.barplot(health_summary, x = 'Country', y = 'mean', errorbar=None)

plt.show()


### barplot with errorbars ###
p = sn.barplot(health_summary, x = 'Country', y = 'mean', errorbar=None)

p.errorbar(x=health_summary['Country'], y=health_summary['mean'], yerr=health_summary['std'], fmt="none", c="k")

plt.show()

答案1

得分: 2

在调用errorbar之前,您需要保存xlim,然后恢复其值。

您可以使用上下文管理器方便地实现:

from contextlib import contextmanager

import matplotlib.pyplot as plt
import seaborn as sns


@contextmanager
def fixed_xlim(ax):
    xlims = ax.get_xlim()
    try:
        yield
    finally:
        ax.set_xlim(xlims)


health = sns.load_dataset("healthexp")
health_summary = (
    health.groupby(["Country"]).Life_Expectancy.agg({"mean", "std"}).reset_index()
)

fig, (ax1, ax2) = plt.subplots(nrows=2)
p = sns.barplot(health_summary, x="Country", y="mean", errorbar=None, ax=ax1)
p = sns.barplot(health_summary, x="Country", y="mean", errorbar=None, ax=ax2)

with fixed_xlim(ax2):
    p.errorbar(
        x=health_summary["Country"],
        y=health_summary["mean"],
        yerr=health_summary["std"],
        fmt="none",
        c="k",
    )

plt.tight_layout()
plt.show()

如何防止pyplot.errorbar导致seaborn barplot的x轴位移

英文:

You need to save the xlim before calling errorbar and then restore its values.

You can make it handy with a context manager:

from contextlib import contextmanager

import matplotlib.pyplot as plt
import seaborn as sns


@contextmanager
def fixed_xlim(ax):
    xlims = ax.get_xlim()
    try:
        yield
    finally:
        ax.set_xlim(xlims)


health = sns.load_dataset("healthexp")
health_summary = (
    health.groupby(["Country"]).Life_Expectancy.agg({"mean", "std"}).reset_index()
)

fig, (ax1, ax2) = plt.subplots(nrows=2)
p = sns.barplot(health_summary, x="Country", y="mean", errorbar=None, ax=ax1)
p = sns.barplot(health_summary, x="Country", y="mean", errorbar=None, ax=ax2)

with fixed_xlim(ax2):
    p.errorbar(
        x=health_summary["Country"],
        y=health_summary["mean"],
        yerr=health_summary["std"],
        fmt="none",
        c="k",
    )

plt.tight_layout()
plt.show()

如何防止pyplot.errorbar导致seaborn barplot的x轴位移

huangapple
  • 本文由 发表于 2023年7月10日 22:55:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/76654976.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定