繁体   English   中英

sns.barplot 绘图上方的文本

[英]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()

在此处输入图像描述

我想在第一张图片中合并这些图形,并从Precipitation中给出所有绘图文本,所以这应该看起来像在此处输入图像描述

这里似乎有一个解决方案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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM