ler*_*ygr 60 python plot matplotlib dataframe pandas
我正在寻找一种方法来使用我的DataFrame中的舍入数值来在Pandas条形图中注释我的条形图.
>>> 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
Run Code Online (Sandbox Code Playgroud)
我想得到这样的东西:
我尝试使用此代码示例,但注释都集中在x刻度上:
>>> 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')
Run Code Online (Sandbox Code Playgroud)
Tom*_*ger 98
你直接从轴的补丁得到它:
In [35]: for p in ax.patches:
ax.annotate(str(p.get_height()), (p.get_x() * 1.005, p.get_height() * 1.005))
Run Code Online (Sandbox Code Playgroud)
你需要调整字符串格式和偏移以使事物居中,也许使用宽度p.get_width()
,但这应该让你开始.除非您在某处跟踪偏移,否则它可能不适用于堆积条形图.
two*_*rec 25
采用样品浮法成型处理的解决方案也可以处理负值.
仍然需要调整补偿.
df=pd.DataFrame({'A':np.random.rand(2)-1,'B':np.random.rand(2)},index=['val1','val2'] )
ax = df.plot(kind='bar', color=['r','b'])
x_offset = -0.03
y_offset = 0.02
for p in ax.patches:
b = p.get_bbox()
val = "{:+.2f}".format(b.y1 + b.y0)
ax.annotate(val, ((b.x0 + b.x1)/2 + x_offset, b.y1 + y_offset))
Run Code Online (Sandbox Code Playgroud)
tdy*_*tdy 15
Axes.bar_label
为自动标记条形图添加了新的辅助方法。
对于单组条形图,请提供ax.containers[0]
:
df = pd.DataFrame({'A': np.random.rand(2)}, index=['value1', 'value2'])
ax = df.plot.barh()
ax.bar_label(ax.containers[0])
Run Code Online (Sandbox Code Playgroud)
对于多组条形图,迭代ax.containers
:
df = pd.DataFrame({'A': np.random.rand(2), 'B': np.random.rand(2)}, index=['value1', 'value2'])
ax = df.plot.bar()
for container in ax.containers:
ax.bar_label(container)
Run Code Online (Sandbox Code Playgroud)
有关使用可选样式参数的综合示例,请参阅matplotlib 的条形标签演示:
Axes.bar_label(self, container, labels=None, *, fmt='%g', label_type='edge', padding=0, **kwargs)
归档时间: |
|
查看次数: |
53082 次 |
最近记录: |