【发布时间】:2019-07-05 21:01:56
【问题描述】:
我遇到了几个问题,但似乎都没有解决注释与 y 刻度标签重叠的问题。我发现了一个很好的代码,可以防止注释相互重叠,但没有刻度标签。
我的问题其实很简单。我使用以下几行来创建我粘贴在它们下方的图形。我使用 annotate 来显示两行的最后一个值是什么。我根据最后一个值与 y 轴总范围的比率来设置注释的位置。它工作得很好,除非注释与刻度标签重叠。这没什么大不了的,但在报告中包含图表时看起来不太好。
这是代码——我省略了操作数据的行:
x = MERVAL.index[(MERVAL.index >= '2014-01-01')]
y1 = MERVAL['MERVAL'][(MERVAL.index >= '2014-01-01')]
y2 = MERVAL['MERVAL_USD'][(MERVAL.index >= '2014-01-01')]
last_date = MERVAL.tail(1).index
right_limit = last_date + datetime.timedelta(days=30)
months = mdates.MonthLocator(1)
monthsFmt = mdates.DateFormatter('%m/%Y')
datemin = datetime.datetime.strptime('01/01/2014', '%m/%d/%Y')
f, ax = plt.subplots()
ax.plot(x,y1, color='b', linewidth=1, label='MERVAL')
ax2 = ax.twinx()
ax2.plot(x,y2, color='r', linewidth=1, label='MERVAL in USD')
ax.set_title('MERVAL',fontsize=20,color='green')
ax.xaxis.set_major_locator(months)
ax.xaxis.set_major_formatter(monthsFmt)
ax.set_xlim(left=datemin, right=right_limit)
ax2.set_xlim(left=datemin, right=right_limit)
ax.grid(axis='x', linestyle=':')
ax.legend(loc=(0.01,0.9))
ax2.legend(loc=(0.01,0.8))
bottom, top = ax.get_ylim()
bottom1, top1 = ax2.get_ylim()
MERVAL_last_price = MERVAL.iloc[-1,0]
MERVAL_USD_last_price = MERVAL.iloc[-1,1]
ax.annotate(str(MERVAL.iloc[-1,0].round(2)), xy=(0,(MERVAL.iloc[-1,0])), xytext=(-0.13 ,((MERVAL_last_price - bottom) / (top - bottom))), xycoords='axes fraction', color='b', annotation_clip=False)
ax2.annotate(str(MERVAL.iloc[-1,1].round(2)), xy=(1,(MERVAL.iloc[-1,1])), xytext=(1.01,((MERVAL_USD_last_price - bottom1) / (top1 - bottom1))), xycoords='axes fraction',color='r', annotation_clip=False)
plt.show()
正如下面评论中所述,我希望红色标签高于(最好是因为它是一个更高的数字)或低于刻度标签)。我知道如何把它带到右边或左边。我也知道如何手动上下移动它。有没有办法让 Matplotlib 检查它是否与刻度标签重叠并自动向上或向下移动?
谢谢
【问题讨论】:
-
我认为很明显我正在努力避免注释与 y 刻度标签重叠,不是吗?
-
刚刚编辑了问题。我希望它能够自动完成,因为我在报告中包含了几个类似这样的图表,这样可以节省我手动移动它们的时间。
-
那里。感谢您对问题的反馈
-
好的,所以解决方案与this one 非常相似,不同之处在于您只需要考虑 1 个标签(您可以检查注释是否与两个标签重叠,在这种情况下没有可能的解决方案)。所以如果重叠了,检查是否需要向上或向下移动,然后依次移动,直到不再重叠。
-
@ImportanceOfBeingErnest 我在发布之前阅读了该帖子,但没有意识到它也可以应用于刻度标签。会尝试。谢谢
标签: python matplotlib annotate