аннотация matplotlib перекрывает метки y_tick на графике - PullRequest
0 голосов
/ 05 августа 2020

Я пробовал несколько разных вещей, чтобы исправить свою диаграмму, от zorder на графиках до plt.rcParams.

Я чувствую, что это такая простая проблема, но я просто не знаю, куда я пошел неправильно. Как вы можете видеть, нижняя аннотация, выделенная голубым синим цветом, нечитаема и смешана с меткой y.

В идеале аннотация располагается над меткой y до точки, где текст внутри аннотации читается.

Если возможно, просто чтобы аннотация располагалась сверху и по-прежнему накладывалась на метку y ... что-то вроде этого

enter image description here
enter image description here

Any help on this would be greatly appreciated.

введите описание изображения здесь



ax = df.plot(x=df.columns[0], y=df.columns[1], legend=False, zorder=0, linewidth=1)
y1 =df.loc[:, df.columns[2]].tail(1)
y2= df.loc[:, df.columns[1]].tail(1)


colors = plt.rcParams["axes.prop_cycle"].by_key()["color"]
print(colors)
for var in (y1, y2):
    plt.annotate('%0.2f' % var.max(), xy=(1, var.max()), zorder=1, xytext=(8, 0), 
                 xycoords=('axes fraction', 'data'), 
                 textcoords='offset points', 
                 bbox=dict(boxstyle="round", fc=colors[0], ec=colors[0],))

ax2 = ax.twinx()
df.plot(x=df.columns[0], y=df.columns[2], ax=ax2, legend=False, color='#fa8174', zorder=0,linewidth=1)


ax.figure.legend(prop=subtitle_font)
ax.grid(True, color="white",alpha=0.2)

pack = [df.columns[1], df.columns[2], freq[0]]
plt.text(0.01, 0.95,'{0} v {1} - ({2})'.format(df.columns[1], df.columns[2], freq[0]),
     horizontalalignment='left',
     verticalalignment='center',
     transform = ax.transAxes,
     zorder=10,
     fontproperties=subtitle_font)

ax.text(0.01,0.02,"Sources: FRED, Quandl, @Paul92s",
    color="white",fontsize=10, 
    horizontalalignment='left', 
    transform = ax.transAxes, 
     verticalalignment='center', 
     zorder=20, 
     fontproperties=subtitle_font)

ax.xaxis.set_major_locator(matplotlib.dates.YearLocator())
ax.xaxis.set_minor_locator(matplotlib.dates.MonthLocator((4,7,10)))
ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter("%Y"))
ax.xaxis.set_minor_formatter(ticker.NullFormatter()) # matplotlib.dates.DateFormatter("%m")
plt.setp(ax.get_xticklabels(), rotation=0, ha="center", zorder=-1)
plt.setp(ax2.get_yticklabels(), rotation=0, zorder=-1)
plt.setp(ax.get_yticklabels(), rotation=0, zorder=-1)
plt.gcf().set_size_inches(14,7)
ax.set_xlabel('Data as of; {0}'.format(df['Date'].max().strftime("%B %d, %Y")), fontproperties=subtitle_font)


y1 =df.loc[:, df.columns[2]].tail(1)
y2= df.loc[:, df.columns[1]].tail(1)

for var in (y1, y2):
    plt.annotate('%0.2f' % var.max(), xy=(1, var.max()), zorder=1,xytext=(8, 0), 
                 xycoords=('axes fraction', 'data'), 
                 textcoords='offset points', 
                 bbox=dict(boxstyle="round", fc="#fa8174", ec="#fa8174"))


plt.title('{0}'.format("FRED Velocity of M2 Money Stock v Trade Weighted U.S. Dollar Index: Broad"),fontproperties=heading_font)
ax.texts.append(ax.texts.pop())
ax.set_facecolor('#181818')
ax.figure.set_facecolor('#181818')
plt.rcParams['axes.axisbelow'] = True

1 Ответ

0 голосов
/ 11 августа 2020

Я не понимаю, почему zorder не работает, но вы можете напрямую установить стиль меток для меток:

import matplotlib.pyplot as plt
import numpy as np
from numpy.random import rand
import matplotlib.patches as mpatches


fig, ax = plt.subplots(1, 1)

ax.plot(rand(100), '^', color='r')

for label in ax.get_xticklabels():
    label.set_bbox(dict(facecolor='orange'))

ax1 = ax.twinx()

ax1.plot(rand(100), 'o', color='b')

index_to_add_bbox = [2, 4]
ax1_labels = ax1.get_yticklabels()

for i in index_to_add_bbox:
    ax1_labels[i].set_bbox(dict(boxstyle='Circle', facecolor='orange'))

plt.show()

введите описание изображения здесь

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...