![](/img/trans.png)
[英]How do I display Y values above the bars in a matplotlib barchart?
[英]How do I display these values above their respective bars on this bar chart with matplotlib? My attempts are not working
我需要在它们各自的条形上方显示值。 完全想不通。 我一直在尝试 for 循环,并被告知可能使用补丁,但我对此还是很陌生并且遇到了一些麻烦。 帮助将不胜感激。 图片包括来自 jupyter notebook 的一小段代码。
这是伪代码
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))
我尝试的实际代码,
for i, value in enumerate(df_dstopics):
label = str(value)
ax.annotate(label, xy=(i, value))
ax.annotate()中的参数xy需要是一个元组,表示坐标系中的一个点。 但是,您的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()
参考:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.