Настройте легенду Python - PullRequest
0 голосов
/ 09 ноября 2018

У меня проблемы с легендами в питоне. В настоящее время у меня есть эти строки, которые показывают, что я хочу в Джулии (используя PyPlot) ...

figure("Something in Julia",figsize=(10,10))
suptitle(L"Something in julia")
# Add text in figure coordinates
figtext(0.5, 0.04, L"Something in julia", ha="center", va="center")

len=collect(-20:4:20);
**legend()
a,=plot(len,QF_r,color="black",linewidth=1.0)#,label="radon");
b,=plot(len,QF_s,color="blue",linewidth=1.0)#,label="sapick");
c,=plot(len,QF_e,color="red",linewidth=1.0)#,label="emd");
legend([a,b,c], ["legen1", "legend2","legend3"],loc="lower right",
       ncol=1,
       fontsize=10,
       markerscale=10,
       markerfirst=true,
       frameon=false,
       fancybox=false,
       shadow=false)**
ax = gca();
xmin, xmax = xlim() # return the current xlim
ymin, ymax = ylim() # return the current xlim
#ylim(ymin=1.0) # adjust the min leaving max unchanged
#ylim(ymax=2.0) # adjust the min leaving max unchanged
ylim(ymin=0.0) # adjust the min leaving max unchanged
ylim(ymax=0.5) # adjust the min leaving max unchanged

xlim(xmin=-20) # adjust the min leaving max unchanged
xlim(xmax=20) # adjust the min leaving max unchanged
xlabel(L"xlabael here $[some units]$", fontsize=14);
ylabel(L"y label here", fontsize=14);
tick_params(axis="both",
    width=1,
    length=1.5,
    direction="in",
    color="black",
    pad=1.5,
    labelsize=10,
    labelcolor="black",
    colors="black",
    zorder=10,
    bottom="on",top="off",left="on",right="off",
    labelbottom="on",labeltop="off",labelleft="on",labelright="off")
    title(L"$\bf{S1}$ $A$ $lot$ $of$ $curves$ $-$ $In$ $julia$", fontsize=12)

Приведенный выше код показывает следующее изображение ... enter image description here

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

Теперь я хочу добиться того же результата в python (импортировать matplotlib.pyplot как plt). Соответствующий код будет что-то вроде ...

plt.legend() 
a,=plt.plot(len,QF_r,color="black",linewidth=1.0)#,label="radon");
b,=plt.plot(len,QF_s,color="blue",linewidth=1.0)#,label="sapick");
c,=plt.plot(len,QF_e,color="red",linewidth=1.0)#,label="emd");
plt.legend([a, b, c], ['label1', 'label2', 'label3'])

что дает мне enter image description here

, в котором вообще НЕТ легенды. Только внешняя рама. Кто-нибудь может мне помочь с этим вопросом? Любая помощь будет высоко ценится.

EDIT: Моя версия на python и matplotlib:

В [564]: import sys

В [565]: печать (sys.version) 2.7.12 (по умолчанию, 4 декабря 2017 г., 14:50:18) [GCC 5.4.0 20160609]

В [566]: импорт matplotlib

In [567]: matplotlib. версия Out [567]: '1.5.1'

и исполняемый код ниже.

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc, font_manager

cos = np.cos
pi = np.pi

##### PARAMETROS
un_lim  = 1.0e-8
nbins   = 25
frec_    = 100.0;
min_db_  = -20;
max_db_  = 20;
stp_db_  = 4;
nexp_    = 100;
nch_     = 8;

xx_r = np.linspace(0,1,   num = nbins);
xx_a = np.linspace(-90,90,num = nbins);
xx_i = np.linspace(-90,90,num = nbins);

db_increment_ = np.arange(min_db_,max_db_+1,stp_db_);
nu_increment_ = len(db_increment_);
ArrayA = np.random.rand(11,100)
ArrayB = np.random.rand(11,100)
ArrayC = np.random.rand(11,100)
len=db_increment_

print(np.shape(ArrayA))
print(np.shape(db_increment_))
pre_tit  = "Something_in_python_Something_in_pyhton"

plt.figure("Something in python",figsize=(10,10))
plt.suptitle(r"Something in python")
# Add text in figure coordinates
plt.figtext(0.5, 0.04, r"Something in python")

plt.legend()
a,=plt.plot(len,ArrayA,color="black",linewidth=1.0)
b,=plt.plot(len,ArrayB,color="blue",linewidth=1.0)
c,=plt.plot(len,ArrayC,color="red",linewidth=1.0)
plt.legend([a,b,c], ["legen1", "legend2","legend3"],loc="lower right",
       ncol=1,
       fontsize=10,
       markerscale=10,
       markerfirst=True,
       frameon=False,
       fancybox=False,
       shadow=False)
xmin, xmax = plt.xlim() # return the current xlim
ymin, ymax = plt.ylim() # return the current xlim
plt.xlabel(r"xlabael here $[some units]$", fontsize=14);
plt.ylabel(r"y label here", fontsize=14);
plt.title(r"It doesnt work in python", fontsize=12)

выдана ошибка:

 44 
 45 plt.legend()

---> 46 a, = plt.plot (len, ArrayA, color = "black", ширина линии = 1,0) 47 b, = plt.plot (len, ArrayB, color = "blue", ширина линии = 1,0) 48 c, = plt.plot (len, ArrayC, color = "red", ширина линии = 1,0)

ValueError: слишком много значений для распаковки

1 Ответ

0 голосов
/ 12 ноября 2018

У вас есть массив формы (11 100) в качестве значений y для ваших plot s. Это означает, что каждый сюжет создает 100 линий. Вы пытаетесь распаковать 100 строк в одну переменную a. Это не работает. Поскольку я не думаю, что вы хотите ввести 100 переменных, разделенных запятой 99, вам лучше вообще не распаковывать результат.

Вместо этого создайте легенду из первого элемента возврата plot.

a = plt.plot(db_increment_, ArrayA, color="black", linewidth=1.0)
b = plt.plot(db_increment_, ArrayB, color="blue", linewidth=1.0)
c = plt.plot(db_increment_, ArrayC, color="red", linewidth=1.0)

plt.legend([a[0], b[0], c[0]], ["legend1", "legend2", "legend3"])
...