如何获得曲线两端都有标签的matplotlib图?

2024-04-28 13:23:47 发布

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

我试图用可用的数据here复制可用的here绘图。你知道吗

seasonal

我已经走了这么远,至少可以说有点混乱。你知道吗

enter image description here

用于获取上述混乱情节的代码如下:

def season_plot():
#robjects.r['load']("./data/a10.rda")
#print(robjects.r['a10'])
#pandas2ri.activate()
#pydf = pd.DataFrame(robjects.r['a10'])
pydf = pd.read_csv('./data/a10.csv',header=None,names=['date','drug_sales'])
dtrng = pd.date_range("1991-07","2008-06",freq='MS')
pydf.set_index(dtrng, inplace=True)
pydf.drop('date', axis=1, inplace=True)
#print(pydf.tail())
pv = pd.pivot_table(pydf,
                index=pydf.index.month,
                columns=pydf.index.year,
                values='drug_sales',
                aggfunc='sum')
fig,ax = plt.subplots()
pv.plot(ax=ax,style='o-',legend=None)
#ax.margins(x=0.15)
for line, name in zip(ax.lines, pv.columns):
    first = line.get_ydata()[0]
    ax.annotate(name, xy=(0,first), xytext=(0,0),
                color=line.get_color(),
                xycoords = ax.get_yaxis_transform(),
                textcoords="offset points",
                size=10, va="center")
for line, name in zip(ax.lines, pv.columns):
    last = line.get_ydata()[-1]
    ax.annotate(name, xy=(1,last), xytext=(0,0),
                color=line.get_color(),
                xycoords = ax.get_yaxis_transform(),
                textcoords="offset points",
                size=10, va="center")

ax.xaxis.set_major_locator(plt.MaxNLocator(13))
xtks = ax.get_xticks().tolist()
xlabels = [calendar.month_abbr[int(x)] if x in range(1,13) else x \
           for x in xtks]
ax.set_xticklabels(xlabels)
plt.title('Antidiabetic drug sales')
plt.ylabel('$ million')
plt.show()

如何将年份标签整齐地排列在第一个图中描述的确切位置?你知道吗

谢谢。你知道吗


Tags: nameingetdateindexlinepltax
1条回答
网友
1楼 · 发布于 2024-04-28 13:23:47

如果没有一些示例数据,很难调试这类问题。也就是说,对我来说,似乎有两个问题:

1)变量xyannotate中的x值似乎不正确,至少对于端点是这样。xy对于结束点应该是xy = line.get_xdata[-1], line.get_ydata[-1];对于开始点也是如此,尽管您对x值的0的guestimate可能是正确的。你知道吗

2)如果不希望标签与数据重叠,则应将偏移点设置为xytext=(0,0)以外的值。(-5,0)(5,0)看起来应该很好,如果您分别为startpoint和endpoint将horizontalalignment设置为'right''left'。你知道吗

相关问题 更多 >