sns.barplot图上的文本

2024-04-24 01:12:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我有如下测试数据:

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()

enter image description here

我也可以用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()

enter image description here

我想在第一幅图中统一这些图形,并给出来自Precipitation的所有绘图文本,所以这应该是 enter image description here


Tags: dfdatasizefigpltaxyearaverage
1条回答
网友
1楼 · 发布于 2024-04-24 01:12:35

这里似乎有一个解决办法 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")

结果是enter image description here

相关问题 更多 >