matplotlib 注释文本位置不正确

问题描述 投票:0回答:1

我正在尝试使用 pandas 绘图方法创建带有注释的堆积条形图。图表中文本的实际位置与 xy 坐标不相符。我尝试了注释方法的 xycoord kwarg 的各种值,但无济于事。我还尝试将axes.text 方法与 transAxes 一起使用。 enter image description here这是我的代码:

import pandas as pd
from matplotlib import pyplot as plt

data = [
    [0.0, 4.9, 19.9, 8.1, 0.0],
    [0.12, 4.5, 27.0, 10.1, 0.0],
    [0.24, 2.8, 9.3, 4.6, 0.0],
    [0.36, 2.2, 9.1, 2.7, 0.0],
    [0.48, 2.2, 7.3, 3.1, 0.0],
    [1.0, 4.9, 26.4, 11.2, 0.0],
    [1.12, 5.9, 25.3, 8.7, 0.0],
    [1.24, 3.7, 13.3, 7.1, 0.0],
    [1.3599999999999999, 3.0, 9.5, 3.4, 0.0],
    [1.48, 3.2, 8.9, 4.7, 0.0],
    [2.0, 8.4, 24.8, 20.2, 0.0],
    [2.12, 9.5, 19.3, 22.5, 0.0],
    [2.24, 5.7, 11.8, 6.6, 0.0],
    [2.36, 4.1, 11.1, 5.1, 0.0],
    [2.48, 5.4, 8.0, 4.6, 0.0],
]
df = pd.DataFrame(columns=["xval", "y1", "y2", "y3", "y4"], data=data)
df1 = df.copy()
fig, ax = plt.subplots()
df1['total'] = df[['y1','y2','y3','y4']].sum(axis = 1)
df.plot(x="xval", kind="bar", ax=ax, stacked=True, width = 0.11)
for (i,x)  in enumerate(df1['xval']):
    ax.annotate('{:.1f}-{:.1f}'.format(x,df1.loc[i]['total']),(x,df1.loc[i]['total']), rotation = 'vertical', fontsize = 10)
xticks, ticklabels = zip(*[(i, x) for i, x in enumerate(df["xval"]) if x.is_integer()])
ax.set_xticks(xticks, ticklabels)
ax.grid()
fig.savefig("mychart.png")

 
pandas matplotlib annotate
1个回答
0
投票

将第二个元组参数中的

x
替换为
i

for (i,x)  in enumerate(df1['xval']):
    ax.annotate('{:.1f}-{:.1f}'.format(x,df1.loc[i]['total']),(x,df1.loc[i]['total']), rotation = 'vertical', fontsize = 10)

->

for (i,x)  in enumerate(df1['xval']):
    ax.annotate('{:.1f}-{:.1f}'.format(x,df1.loc[i]['total']),(i,df1.loc[i]['total']), rotation = 'vertical', fontsize = 10)
© www.soinside.com 2019 - 2024. All rights reserved.