注释多行打印上每列的数据点

2024-05-14 17:38:55 发布

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

我有一个包含多列(列表示月份)的数据框架,每行是一个组,例如

    OCT20  NOV20  DEC20  JAN21
A   20     24     19     18
B   45     29     33     46
C   19     11     13     11

(这只是获得可复制溶液的虚拟数据)

我正在绘制此数据帧的线图,列为x记号,索引中的每一行为图中的一行,每一行中每个月的值为y值

下面是我用来绘图的代码,效果很好。然而,我想用dataframe中的值对每个数据点进行注释,但是通过下面的代码,我可以在一个地方获得所有数据点

%matplotlib inline

labels = ['OCT20', 'NOV20', 'DEC20', 'JAN21', 'FEB21', 'MAR21']

ax = df.T.plot(grid = True, figsize=(20,15), marker='o')

for col in df.columns:
    for id, val in enumerate(df[col]):
        ax.text(id, val, str(val))

x = [0,1,2,3,4,5]
plt.xticks(x, labels, rotation=45)
    
plt.show()

输出是这样的: enter image description here

但我希望每个数据点都对应于绘图中的正确标记

有人知道怎么解决这个问题吗


Tags: 数据代码inid绘图dfforlabels
1条回答
网友
1楼 · 发布于 2024-05-14 17:38:55

你太近了!您已经转置了数据帧,但是尝试通过未转置的数据帧应用文本df

plot_df = df.T  # Save the Transposition
ax = plot_df.plot(grid=True, figsize=(20, 15), marker='o')

for col in plot_df.columns:  # Use the Transposition
    for idx, val in enumerate(plot_df[col]):
        ax.text(idx, val, str(val))

x = [0, 1, 2, 3]
labels = ['OCT20', 'NOV20', 'DEC20', 'JAN21']
plt.xticks(x, labels, rotation=45)

plot


使用的数据帧:

df = pd.DataFrame({
    'OCT20': {'A': 20, 'B': 45, 'C': 19},
    'NOV20': {'A': 24, 'B': 29, 'C': 11},
    'DEC20': {'A': 19, 'B': 33, 'C': 13},
    'JAN21': {'A': 18, 'B': 46, 'C': 11}
})

相关问题 更多 >

    热门问题