matplotlib 如何防止pyplot.errorbar偏移海运条形图的x轴

vlf7wbxs  于 2023-08-06  发布在  其他
关注(0)|答案(1)|浏览(77)

我想使用Seaborn条形图绘制数据;我只有平均值和标准差。我使用pyplot.errorbar向图中添加误差线,但是它会稍微移动x轴(请参见图中的星星)。我如何防止这种情况发生?
图:x1c 0d1x
复制代码:

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()

字符串

yi0zb3m4

yi0zb3m41#

您需要在调用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()

字符串


的数据

相关问题