【问题标题】:Add Text/Annotations to stacked barplot Python [duplicate]将文本/注释添加到堆叠的条形图 Python [重复]
【发布时间】:2021-12-28 22:00:41
【问题描述】:

我想通过('Rank')而不是图例在单个类别/栏的中间添加文本。请告知这是否可以在 python 中实现?

我的代码如下:

ax = sns.histplot(data=dfnew2, multiple='stack', x = 'Purpose', weights = 'Credit amount', hue='Rank',shrink=0.8, legend = True)
ax.set(ylabel='Credit Amount', xlabel='Purpose')
ax.tick_params(axis="x", labelrotation=90)

【问题讨论】:

  • 检查ax.annotateax.text。如果您需要帮助来实现它,请提供一个最小的可重现示例。

标签: python seaborn bar-chart histogram


【解决方案1】:

您可以使用:

ax.text()

检查这个与 for 循环一起使用的站点示例,就像您的数据一样。

https://www.tutorialspoint.com/how-to-write-text-above-the-bars-on-a-bar-plot-python-matplotlib

【讨论】:

  • 嗨,我发现这是最合适的。谢谢
【解决方案2】:

由于您没有提供代码示例,请尝试使用您的变量进行调整 它会按照你的要求工作:

x = np.arange(len(years)) # the label locations
width = 0.35 # the width of the bars
fig, ax = plt.subplots()
ax.set_ylabel('Population(in million)')
ax.set_title('Years')
ax.set_xticks(x)
ax.set_xticklabels(years)
pps = ax.bar(x, population, width, label='population')
for p in pps:
    height = p.get_height()
    ax.text(x=p.get_x() + p.get_width() / 2, y=height/2.5,
            s="{}".format(height),
            ha='center',
            rotation=90
            )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 2019-04-15
    • 2023-02-10
    • 2019-01-30
    相关资源
    最近更新 更多