Как настроить размер окна легенды matplotlib?

У меня есть график, левый верхний угол которого довольно пуст. Поэтому я решил разместить свою легендарную коробку.

Однако я считаю, что элементы в легенде очень маленькие, а <легендa > также довольно маленькая.

Под "маленьким" я имею в виду что-то вроде этого

enter image description here

Как я могу сделать элементы (а не тексты!) в окне легенды больше?

Как я могу увеличить размер коробки?

Ответы

Ответ 1

Чтобы управлять надписью внутри легенды (эффективно увеличивая размер окна легенды), используйте borderpad kwarg.

Например, здесь значение по умолчанию:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)

fig, ax = plt.subplots()
for i in range(1, 6):
    ax.plot(x, i*x + x, label='$y={i}x + {i}$'.format(i=i))
ax.legend(loc='upper left')
plt.show()

enter image description here


Если мы изменим внутри padding с помощью borderpad=2, мы сделаем общее поле легенды больше (единицы кратности размера шрифта, похожие на em):

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)

fig, ax = plt.subplots()
for i in range(1, 6):
    ax.plot(x, i*x + x, label='$y={i}x + {i}$'.format(i=i))
ax.legend(loc='upper left', borderpad=2)
plt.show()

enter image description here


В качестве альтернативы вы можете изменить интервал между элементами. Используйте labelspacing для управления этим:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)

fig, ax = plt.subplots()
for i in range(1, 6):
    ax.plot(x, i*x + x, label='$y={i}x + {i}$'.format(i=i))
ax.legend(loc='upper left', labelspacing=2)
plt.show()

enter image description here


В большинстве случаев, однако, имеет смысл регулировать одновременно labelspacing и borderpad:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)

fig, ax = plt.subplots()
for i in range(1, 6):
    ax.plot(x, i*x + x, label='$y={i}x + {i}$'.format(i=i))
ax.legend(loc='upper left', borderpad=1.5, labelspacing=1.5)
plt.show()

enter image description here


С другой стороны, если у вас очень большие маркеры, вы можете увеличить длину строки, показанной в легенде. Например, значение по умолчанию может выглядеть примерно так:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 5)

fig, ax = plt.subplots()
for i in range(1, 6):
    ax.plot(x, i*x + x, marker='o', markersize=20,
            label='$y={i}x + {i}$'.format(i=i))
ax.legend(loc='upper left')
plt.show()

enter image description here

Если мы изменим handlelength, мы получим более длинные строки в легенде, которая выглядит несколько более реалистичной. (Я также настраиваю borderpad и labelspacing здесь, чтобы дать больше места.)

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 5)

fig, ax = plt.subplots()
for i in range(1, 6):
    ax.plot(x, i*x + x, marker='o', markersize=20,
            label='$y={i}x + {i}$'.format(i=i))
ax.legend(loc='upper left', handlelength=5, borderpad=1.2, labelspacing=1.2)
plt.show()

enter image description here


В документах приведены некоторые другие параметры, которые вы можете изучить:

Padding and spacing between various elements use following
keywords parameters. These values are measure in font-size
units. E.g., a fontsize of 10 points and a handlelength=5
implies a handlelength of 50 points.  Values from rcParams
will be used if None.

=====================================================================
Keyword       |    Description
=====================================================================
borderpad          the fractional whitespace inside the legend border
labelspacing       the vertical space between the legend entries
handlelength       the length of the legend handles
handletextpad      the pad between the legend handle and text
borderaxespad      the pad between the axes and legend border
columnspacing      the spacing between columns

Ответ 2

Когда вы вызываете легенду, вы можете использовать аргумент prop с размером, содержащим dict.

plt.errorbar(x, y, yerr=err, fmt='-o', color='k', label = 'DR errors')
plt.legend(prop={'size':50})

например. change legend size

Подробнее см. здесь legend