在 Pandas 条形图上用值注释条形

编程入门 行业动态 更新时间:2024-10-06 14:33:18
本文介绍了在 Pandas 条形图上用值注释条形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我一直在寻找一种方法,用我的 DataFrame 中的舍入数值来注释 Pandas 条形图中的条形.

>>>df=pd.DataFrame({'A':np.random.rand(2),'B':np.random.rand(2)},index=['value1','value2'])>>>df甲乙值 1 0.440922 0.911800值 2 0.588242 0.797366

我想得到这样的东西:

我尝试使用此代码示例,但注释都以 x 刻度为中心:

>>>ax = df.plot(kind='bar')>>>对于 idx,enumerate(list(df.index)) 中的标签:对于 df.columns 中的 acc:值 = np.round(df.ix[idx][acc],decimals=2)ax.annotate(值,(idx, 值),xytext=(0, 15),textcoords='偏移点')

解决方案

您可以直接从轴的补丁中获取它:

for p in ax.patches:ax.annotate(str(p.get_height()), (p.get_x() * 1.005, p.get_height() * 1.005))

您需要调整字符串格式和偏移量以使内容居中,也许可以使用 p.get_width() 中的宽度,但这应该会让您开始.除非您在某处跟踪偏移量,否则它可能不适用于堆叠条形图.

I was looking for a way to annotate my bars in a Pandas bar plot with the rounded numerical values from my DataFrame.

>>> df=pd.DataFrame({'A':np.random.rand(2),'B':np.random.rand(2)},index=['value1','value2'] ) >>> df A B value1 0.440922 0.911800 value2 0.588242 0.797366

I would like to get something like this:

I tried with this code sample, but the annotations are all centered on the x ticks:

>>> ax = df.plot(kind='bar') >>> for idx, label in enumerate(list(df.index)): for acc in df.columns: value = np.round(df.ix[idx][acc],decimals=2) ax.annotate(value, (idx, value), xytext=(0, 15), textcoords='offset points')

解决方案

You get it directly from the axes' patches:

for p in ax.patches: ax.annotate(str(p.get_height()), (p.get_x() * 1.005, p.get_height() * 1.005))

You'll want to tweak the string formatting and the offsets to get things centered, maybe use the width from p.get_width(), but that should get you started. It may not work with stacked bar plots unless you track the offsets somewhere.

更多推荐

在 Pandas 条形图上用值注释条形

本文发布于:2023-07-18 08:13:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1142732.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:条形   注释   图上   Pandas

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!