Подтвердить что ты не робот

Как я могу сделать одну легенду для многих подзаговоров с matplotlib?

Я рисую один и тот же тип информации, но для разных стран, с несколькими подзаголовками с matplotlib. То есть, у меня 9 графиков в сетке 3x3, все они одинаковы для строк (разумеется, разные значения для каждой строки).

Однако я не понял, как поставить одну легенду (так как все 9 подзаголовков имеют одинаковые строки) на рисунке только один раз.

Как это сделать?

4b9b3361

Ответ 2

Существует также хорошая функция get_legend_handles_labels(), которую вы можете вызывать на последней оси (если вы перебираете их), которая собирала бы все, что вам нужно, из аргументов label=:

handles, labels = ax.get_legend_handles_labels()
fig.legend(handles, labels, loc='upper center')

Ответ 3

Вам просто нужно попросить легенду один раз, вне вашей петли.

Например, в этом случае у меня есть 4 подзаголовка с одинаковыми строками и одна легенда.

from matplotlib.pyplot import *

ficheiros = ['120318.nc', '120319.nc', '120320.nc', '120321.nc']

fig = figure()
fig.suptitle('concentration profile analysis')

for a in range(len(ficheiros)):
    # dados is here defined
    level = dados.variables['level'][:]

    ax = fig.add_subplot(2,2,a+1)
    xticks(range(8), ['0h','3h','6h','9h','12h','15h','18h','21h']) 
    ax.set_xlabel('time (hours)')
    ax.set_ylabel('CONC ($\mu g. m^{-3}$)')

    for index in range(len(level)):
        conc = dados.variables['CONC'][4:12,index] * 1e9
        ax.plot(conc,label=str(level[index])+'m')

    dados.close()

ax.legend(bbox_to_anchor=(1.05, 0), loc='lower left', borderaxespad=0.)
         # it will place the legend on the outer right-hand side of the last axes

show()

Ответ 4

Для автоматического позиционирования одной легенды в figure со многими осями, как и при использовании subplots(), следующее решение работает очень хорошо:

plt.legend( lines, labels, loc = 'lower center', bbox_to_anchor = (0,-0.1,1,1),
            bbox_transform = plt.gcf().transFigure )

С bbox_to_anchor и bbox_transform=plt.gcf().transFigure вы определяете новый ограничивающий прямоугольник размера вашего figure как ссылку для loc. Использование (0,-0.1,1,1) перемещает эту коробку боулинга немного вниз, чтобы предотвратить нанесение легенды другим художникам.

OBS: используйте это решение ПОСЛЕ использования fig.set_size_inches() и ПЕРЕД тем, как вы используете fig.tight_layout()

Ответ 5

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

enter image description here

Теперь вы хотите посмотреть код, не так ли?

from numpy import linspace
import matplotlib.pyplot as plt

# Calling the axes.prop_cycle returns an itertoools.cycle

color_cycle = plt.rcParams['axes.prop_cycle']()

# I need some curves to plot

x = linspace(0, 1, 51)
f1 = x*(1-x)   ; lab1 = 'x - x x'
f2 = 0.25-f1   ; lab2 = '1/4 - x + x x' 
f3 = x*x*(1-x) ; lab3 = 'x x - x x x'
f4 = 0.25-f3   ; lab4 = '1/4 - x x + x x x'

# let plot our curves (note the use of color cycle, otherwise the curves colors in
# the two subplots will be repeated and a single legend becomes difficult to read)
fig, (a13, a24) = plt.subplots(2)

a13.plot(x, f1, label=lab1, **next(color_cycle))
a13.plot(x, f3, label=lab3, **next(color_cycle))
a24.plot(x, f2, label=lab2, **next(color_cycle))
a24.plot(x, f4, label=lab4, **next(color_cycle))

# so far so good, now the trick

lines_labels = [ax.get_legend_handles_labels() for ax in fig.axes]
lines, labels = [sum(lol, []) for lol in zip(*lines_labels)]

# finally we invoke the legend (that you probably would like to customize...)

fig.legend(lines, labels)
plt.show()

Две строки

lines_labels = [ax.get_legend_handles_labels() for ax in fig.axes]
lines, labels = [sum(lol, []) for lol in zip(*lines_labels)]

заслуживает объяснения - для этой цели я вложил сложную часть в функцию, всего 4 строки кода, но сильно прокомментировал

def fig_legend(fig, **kwdargs):

    # generate a sequence of tuples, each contains
    #  - a list of handles (lohand) and
    #  - a list of labels (lolbl)
    tuples_lohand_lolbl = (ax.get_legend_handles_labels() for ax in fig.axes)
    # e.g. a figure with two axes, ax0 with two curves, ax1 with one curve
    # yields:   ([ax0h0, ax0h1], [ax0l0, ax0l1]) and ([ax1h0], [ax1l0])

    # legend needs a list of handles and a list of labels, 
    # so our first step is to transpose our data,
    # generating two tuples of lists of homogeneous stuff(tolohs), i.e
    # we yield ([ax0h0, ax0h1], [ax1h0]) and ([ax0l0, ax0l1], [ax1l0])
    tolohs = zip(*tuples_lohand_lolbl)

    # finally we need to concatenate the individual lists in the two
    # lists of lists: [ax0h0, ax0h1, ax1h0] and [ax0l0, ax0l1, ax1l0]
    # a possible solution is to sum the sublists - we use unpacking
    handles, labels = (sum(list_of_lists, []) for list_of_lists in tolohs)

    # call fig.legend with the keyword arguments, return the legend object

    return fig.legend(handles, labels, **kwdargs)

PS Я признаю, что sum(list_of_lists, []) является действительно неэффективным методом сглаживания списка списков, но "мне нравится его компактность", обычно это несколько кривых в нескольких сюжетах и "Matplotlib и эффективность"? ;-)

Ответ 6

Хотя довольно поздно в игре, я дам еще одно решение, так как это все еще одна из первых ссылок на google. Используя matplotlib 2.2.2, это может быть достигнуто с использованием функции gridspec. В приведенном ниже примере цель состоит в том, чтобы иметь четыре подзаголовка, расположенных по схеме 2x2, с легендой, показанной внизу. Ось "faux" создается внизу, чтобы разместить легенду в фиксированном месте. Затем ось "faux" выключается, поэтому отображается только легенда. Результат: https://i.stack.imgur.com/5LUWM.png.

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

#Gridspec demo
fig = plt.figure()
fig.set_size_inches(8,9)
fig.set_dpi(100)

rows   = 17 #the larger the number here, the smaller the spacing around the legend
start1 = 0
end1   = int((rows-1)/2)
start2 = end1
end2   = int(rows-1)

gspec = gridspec.GridSpec(ncols=4, nrows=rows)

axes = []
axes.append(fig.add_subplot(gspec[start1:end1,0:2]))
axes.append(fig.add_subplot(gspec[start2:end2,0:2]))
axes.append(fig.add_subplot(gspec[start1:end1,2:4]))
axes.append(fig.add_subplot(gspec[start2:end2,2:4]))
axes.append(fig.add_subplot(gspec[end2,0:4]))

line, = axes[0].plot([0,1],[0,1],'b')           #add some data
axes[-1].legend((line,),('Test',),loc='center') #create legend on bottommost axis
axes[-1].set_axis_off()                         #don't show bottommost axis

fig.tight_layout()
plt.show()

Ответ 7

Этот ответ является дополнением к @Evert в позиции легенды.

Моя первая попытка при решении @Evert завершилась неудачей из-за совпадений легенды и заголовка подзаголовка.

На самом деле перекрытия вызваны fig.tight_layout(), что изменяет макет подзаголовков без учета легенды фигуры. Однако fig.tight_layout() необходимо.

Чтобы избежать перекрытий, мы можем сказать fig.tight_layout() оставить пробелы для условного обозначения фигуры fig.tight_layout(rect=(0,0,1,0.9)).

Описание параметров tight_layout().

Ответ 8

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

Скажем, у вас есть четыре бара с различными цветами, как r m c k вы можете установить легенду следующим образом

import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
labels = ['Red Bar', 'Magenta Bar', 'Cyan Bar', 'Black Bar']


#####################################
# insert code for the subplots here #
#####################################


# now, create an artist for each color
red_patch = mpatches.Patch(facecolor='r', edgecolor='#000000') #this will create a red bar with black borders, you can leave out edgecolor if you do not want the borders
black_patch = mpatches.Patch(facecolor='k', edgecolor='#000000')
magenta_patch = mpatches.Patch(facecolor='m', edgecolor='#000000')
cyan_patch = mpatches.Patch(facecolor='c', edgecolor='#000000')
fig.legend(handles = [red_patch, magenta_patch, cyan_patch, black_patch],labels=labels,
       loc="center right", 
       borderaxespad=0.1)
plt.subplots_adjust(right=0.85) #adjust the subplot to the right for the legend