[英]sns.barplot text above plots
我有测试数据,如:
d = {'Year':[2015,2016,2017,2018,2019,2020],
'Average Temperature, C':[15, 16, 14, 13, 17, 17],
'Precipitation':[1,2,3,4,5,6]}
所以我的 df 是df = pd.DataFrame(data=d)
然后我想用Temperature
的含义来形象化这个,所以
fig, ax = plt.subplots()
fig.set_size_inches(11.7,8.27)
sns.barplot(x='Year', y='Average Temperature, C', data=df, ax=ax)
sns.despine()
我也可以用Precipitation
意义来做到这一点
fig, ax = plt.subplots()
fig.set_size_inches(11.7,8.27)
sns.barplot(x='Year', y='Precipitation', data=df, ax=ax)
sns.despine()
这里似乎有一个解决方案Seaborn 条形图 - 显示值(在我发布以下答案后发现)
但这是另一种方法。
df = {'Year':[2015,2016,2017,2018,2019,2020],
'Average Temperature, C':[15, 16, 14, 13, 17, 17],
'Precipitation':[1,2,3,4,5,6]}
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
fig.set_size_inches(11.7,8.27)
rects =ax.bar(x=df['Year'],height=df['Average Temperature, C'])
def autolabel(rects, pvalue, xpos='center',):
"""
Attach a text label above each bar in *rects*, displaying its height.
*xpos* indicates which side to place the text w.r.t. the center of
the bar. It can be one of the following {'center', 'right', 'left'}.
"""
xpos = xpos.lower() # normalize the case of the parameter
ha = {'center': 'center', 'right': 'left', 'left': 'right'}
offset = {'center': 0.5, 'right': 0.57, 'left': 0.43} # x_txt = x + w*off
for i, rect in enumerate(rects):
height = rect.get_height()
ax.text(rect.get_x() + rect.get_width()*offset[xpos], 1.01*height,
'{}'.format(pvalue[i]), ha=ha[xpos], va='bottom')
autolabel(rects,df['Precipitation'], "left")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.