使用数据框和基本图如下:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(123456)
rows = 75
df = pd.DataFrame(np.random.randint(-4,5,size=(rows, 3)), columns=['A', 'B', 'C'])
datelist = pd.date_range(pd.datetime(2017, 1, 1).strftime('%Y-%m-%d'), periods=rows).tolist()
df['dates'] = datelist
df = df.set_index(['dates'])
df.index = pd.to_datetime(df.index)
df = df.cumsum()
df.plot()
注释线上最后几点的最佳方法是什么,以便得到下面的结果?
答案 0 :(得分:9)
为了注释点使用ax.annotate()
。在这种情况下,指定要单独注释的坐标是有意义的。即y坐标是该行的最后一个点的数据坐标(可以从line.get_ydata()[-1]
获得),而x坐标与数据无关,应该是轴的右侧(即{{1在轴坐标中)。然后,您可能还想稍微偏移文本,使其不与轴重叠。
1
答案 1 :(得分:4)
方法1
这是一种方法,或者至少是一种方法,您可以使用plt.annotate
方法以任何您想要的方式适应美学:
[编辑]:如果你要使用像这样的方法,那么ImportanceOfBeingErnest的答案中概述的方法比我提出的方法更好。
df.plot()
for col in df.columns:
plt.annotate(col,xy=(plt.xticks()[0][-1]+0.7, df[col].iloc[-1]))
plt.show()
对于xy
参数,即文本的x和y坐标,我选择plt.xticks()
中的最后一个x坐标,并添加0.7以使其超出x轴,但是你可以在你认为合适的时候使它更近或更近。
方法2 :
您也可以使用正确的y轴,并用3行标记它。例如:
fig, ax = plt.subplots()
df.plot(ax=ax)
ax2 = ax.twinx()
ax2.set_ylim(ax.get_ylim())
ax2.set_yticks([df[col].iloc[-1] for col in df.columns])
ax2.set_yticklabels(df.columns)
plt.show()
这会给你以下情节: