向Matplotlib折线图上的每个第3个标记添加文本

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

我已经创建了下面的图表,在每个数据点均带有文本。我想要的是在标记上显示每个第3个文本。行将保留,但每个数据点的文本应跳过两个。因此,我希望能看到同一行,但是文本仅占10%,40%,70%和100%。

这是我的代码:

import pandas as pd
from matplotlib import pyplot as plt

x = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
y = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct']

df = pd.DataFrame(list(zip(x,y)), columns=['Percentages', 'Months'])

fig, ax = plt.subplots()
ax.plot(df['Months'], df['Percentages'], color='#0076B6', dashes=[6, 2], marker='o')
for j, v in enumerate(df['Percentages']):
    ax.text(j, v+2, str('{:.2f}'.format(round(v, 2)))+'%', fontsize=5.5, horizontalalignment='center')
plt.show()

enter image description here

希望如此,有人可以帮忙。

谢谢,

Aksel

python matplotlib text annotations
1个回答
1
投票

仅在每三个元素上循环:

for j, v in enumerate(df['Percentages'][::3]):
    ax.text(j*3, ...)
© www.soinside.com 2019 - 2024. All rights reserved.