Ошибка печати легенды с помощью matplotlib и y twinx - PullRequest
0 голосов
/ 11 апреля 2020

Здравствуйте, я пытаюсь напечатать график с множеством линий с легенами, у меня есть следующий код:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
from math import sqrt

font = {'family' : 'normal',
        'weight' : 'bold',
        'size'   : 22}

rc('font', **font)
rc('text', usetex=True)

fig = plt.figure(figsize=(15,10))
ax = fig.add_subplot(111)


lns1 = ax.plot(test_err, label = 'Error test')
lns2 = ax.plot(oob_rates, label = 'Error oob')

ax2 = ax.twinx()
lns3 = ax2.plot(times, '-r', label = 'Segundos')


lns = lns1+lns2+lns3
labs = [l.get_label() for l in lns]
ax.legend(lns, labs, loc=1, bbox_to_anchor=(1, 1))


ax.grid()
ax.set_xlabel("m - Número máximo de variables usadas por el árbol")
ax.set_ylabel("Error")
ax2.set_ylabel("Tiempo ejecucion")

ax.axvline(sqrt(58), 0, 1, label=r'$m=\sqrt{p}$', c='g', linestyle='dashed')
ax.legend(loc=1)

ax.axhline((min(test_err)), 0, 1, label='Min test error', c='b', linestyle='dashed')
ax.legend(loc=1,  bbox_to_anchor=(1.4, 1))


plt.show()

И я получаю следующий график:

enter image description here

Проблема в том, что красная линия не печатается в поле легенды.

Как ее решить?

Спасибо

1 Ответ

0 голосов
/ 12 апреля 2020

Я обновил свой ответ, чтобы получить легенду снаружи:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
from math import sqrt

test_err=np.random.uniform(0,1,10)
oob_rates=np.random.uniform(0,1,10)
times=np.random.uniform(0,1,10)

font = {'family' : 'normal',
    'weight' : 'bold',
    'size'   : 22}

rc('font', **font)
rc('text', usetex=True)

fig = plt.figure(figsize=(15,10))
ax = fig.add_subplot(111)


lns1 = ax.plot(test_err, label = 'Error test')
lns2 = ax.plot(oob_rates, label = 'Error oob')

ax2 = ax.twinx()
lns3 = ax2.plot(times, '-r', label = 'Segundos')

ax.grid()
ax.set_xlabel("m - Número máximo de variables usadas por el árbol")
ax.set_ylabel("Error")
ax2.set_ylabel("Tiempo ejecucion")

lns4=ax.axvline(sqrt(58), 0, 1, label=r'$m=\sqrt{p}$', c='g', linestyle='dashed')
ax.legend(loc=1)

lns5=ax.axhline((min(test_err)), 0, 1, label='Min test error', c='b', linestyle='dashed')
ax.legend(loc=1,  bbox_to_anchor=(1.4, 1))

lns = lns1+lns2+lns3+[lns4]+[lns5]
labs = [l.get_label() for l in lns]
ax.legend(lns, labs, loc=1, bbox_to_anchor=(0, 0, 1.2, 1), bbox_transform=plt.gcf().transFigure)

plt.show()

Ниже мой вывод (я сделал фиктивные данные):

two_axis_legend

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