[英]How do I display these values above their respective bars on this bar chart with matplotlib? My attempts are not working
I need to display the values above their respective bars.我需要在它们各自的条形上方显示值。 Can't quite figure it out.完全想不通。 I have been trying for loops, and was told to possibly use patches but I'm pretty new at this still and having some trouble.我一直在尝试 for 循环,并被告知可能使用补丁,但我对此还是很陌生并且遇到了一些麻烦。 Help would be appreciated.帮助将不胜感激。 The pictures include the short bit of code from the jupyter notebook.图片包括来自 jupyter notebook 的一小段代码。
Here is the pseudocode这是伪代码
df=read_csv
df.sort_values
df = df/2233*100.round
ax=df.plot(bar)
ax.set_title
ax.tick_params
ax.legend
for i, value in enumerate(df):
label=str(value)
ax.annotate(label, xy=(i, value))
The actual code I try,我尝试的实际代码,
for i, value in enumerate(df_dstopics):
label = str(value)
ax.annotate(label, xy=(i, value))
Parameter xy in ax.annotate() needs to be a tuple which represents a point in coordinate system. ax.annotate()中的参数xy需要是一个元组,表示坐标系中的一个点。 However, the value
in your for i, value in enumerate(df)
is column name, which is definitely not a valid constant.但是,您的for i, value in enumerate(df)
value
的值是列名,这绝对不是有效的常量。
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
df = pd.DataFrame({'Very interested':np.random.rand(2), 'Somewhat interested':np.random.rand(2)+1, 'Not interested':np.random.rand(2)+2})
ax = df.plot(kind='bar', color=['r','b','g'])
for p in ax.patches:
ax.annotate(s=np.round(p.get_height(), decimals=2),
xy=(p.get_x()+p.get_width()/2., p.get_height()),
ha='center',
va='center',
xytext=(0, 10),
textcoords='offset points')
plt.show()
Reference:参考:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.