我无法完成应该足够简单的事情,这使我发疯。我有一个按年份分组的时间序列,以便可以绘制每年并进行比较。当我绘制时,我有21条线,所以我想在每条线的末尾添加年份而不是图例框,例如此处的图形(示例):
我已经创建了一个函数,可以获取任何时间序列并返回此图,并且我正努力添加此自定义标签/注释。
我的代码是这样的:
def plot_by_year(ts):
# first I group the time series (ts) by year:
year_group = ts.groupby(pd.Grouper(freq ='A'))
yearly = pd.DataFrame()
for year, group in year_group:
yearly[year.year] = group.values.ravel()
# now to plot it, the easy mode is:
yearly.plot(figsize = (12,14), legend=True)
plt.gca().legend(loc='center left', bbox_to_anchor=(1, .5));
但是,这仅在图外给了我一个图例框(请参见下面的图)
我在this instructions之后尝试的替代方法是这样的:
for rank, column in enumerate(years):
plt.plot(np.arange(0,13), yearly[column].values, lw=2.5)
y_pos = yearly[column].values[-1] - 0.5
plt.text(12, y_pos, rank)
这给了我
KeyError: 1996
,这是我数据的第一年。我已经尝试了很多事情,甚至都不知道自己在做什么。救命! 最佳答案
听起来您的years
与yearly.columns
不同。也许您只是弄错了数据类型(int与字符串?)。尝试以下方法:
fig, ax = plt.subplots() # probably unnecessary tbh but I prefer working with the ax obj rather than plt
n_points = yearly.shape[0] # generalize out that 12. This is the number of points in your series. If it's months then I guess it's always 12...
for year in yearly: # get the column names straight off the dataframe
ax.plot(np.arange(n_points), yearly[year].values, lw=2.5)
y_pos = yearly[year].values[-1] - 0.5
ax.text(n_points, y_pos, year) # You wanted to label it with the column name, not the column index which is what rank would have given you
关于python - 将标签添加到按年线图分组的时间序列上-Matplotlib,Python,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58437089/