python - sns.barplot 绘图上方的文本
问题描述
我有测试数据,如:
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 Barplot - Displaying Values(在我发布以下答案后发现)
但这是另一种方法。
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")
推荐阅读
- sql - 在实体框架核心中,当两个字段映射到另一个表的主键时,我们如何为一个表设置关系
- node.js - 如何在 ExpressJs (NODE.JS) 中实现/处理异常
- ionic-framework - StatusBar 没有 web 实现
- reactjs - React、Django、Django REST 和 Axios 的大量问题
- swift - SwiftUI 从另一个 swift 类调用辅助函数?
- flutter - Flutter 中的 Widgets Library 错误捕获的异常
- node.js - Nuxt 和 Vue 部署在同一个域中
- docker - 如何在 Azure Web 应用服务上部署完善的工作流程?
- flutter - 如何将彩色图像转换为黑白
- excel - 如何根据数据透视表中总计的更改使用 VBA 更改 Excel 文件是否可见(最小化)?