如何使用python和matplotlib注释行尾? [英] How to annotate end of lines using python and matplotlib?
问题描述
具有这样的数据框和基本图:
With a dataframe and basic plot such as this:
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()
注释行中最后一点的最佳方法是什么,以便获得以下结果?
What is the best way of annotating the last points on the lines so that you get the result below?
推荐答案
要注释点,请使用ax.annotate()
.在这种情况下,有必要指定要单独注释的坐标. IE. y坐标是线的最后一点的数据坐标(您可以从line.get_ydata()[-1]
获取),而x坐标与数据无关,并且应位于轴的右侧(即,轴中的1
坐标).然后,您可能还需要稍微偏移文本,使其与轴不重叠.
In order to annotate a point use ax.annotate()
. In this case it makes sense to specify the coordinates to annotate separately. I.e. the y coordinate is the data coordinate of the last point of the line (which you can get from line.get_ydata()[-1]
) while the x coordinate is independent of the data and should be the right hand side of the axes (i.e. 1
in axes coordinates). You may then also want to offset the text a bit such that it does not overlap with the axes.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
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()
ax = df.plot()
for line, name in zip(ax.lines, df.columns):
y = line.get_ydata()[-1]
ax.annotate(name, xy=(1,y), xytext=(6,0), color=line.get_color(),
xycoords = ax.get_yaxis_transform(), textcoords="offset points",
size=14, va="center")
plt.show()
这篇关于如何使用python和matplotlib注释行尾?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!