Messing labels colors in matplotlib

I'm plotting data from a dict which has three keys:

[u'Ferronikel', u'Nicromo', u'Alambre_1']

And each one of this have several params like resistances, voltage an a like so I'm using a function to plot the values easily.

def graficar_parametro(x,y):

    d_unidades = {'I':'A','V':'V','R':'ohm','T':'C','P':'W/m'}
    for alambre in sorted(alambres.keys()):
        model = sklearn.linear_model.LinearRegression()


        X = alambres[alambre]['mediciones'][x].reshape(-1, 1)
        Y = alambres[alambre]['mediciones'][y].reshape(-1, 1)
        model.fit(X,Y)


        x_label = d_unidades[x]
        y_label = d_unidades[y]
        plt.legend(sorted(alambres.keys()))
        plt.xlabel(x_label)
        plt.ylabel(y_label)
        plt.plot(X,Y,'8',
                X, model.predict(X),'-')
    plt.title('Heating wires')

    plt.show()

To plot Voltage vs current I run:

graficar_parametro('I','V')

And got this images:

enter image description here

But there the colors are wrong:

Blue dots correspond to 'Alambre_1' that one is fine, but yellow dots should be labeled as 'Nicromo' and ferronikel should have the red dots not a green line.

I thought to use sorted would solve the issue, but it doesn't fix it.

for alambre in sorted(alambres.keys()):
       plt.legend(sorted(alambres.keys()))

Upvotes: 0

Views: 84

Answers (1)

Vadim Shkaberda
Vadim Shkaberda

Reputation: 2936

One way to do so is to make storage for matplotlib objects. And you need to distinguish dot- and line-plots.

def graficar_parametro(x,y):

d_unidades = {'I':'A','V':'V','R':'ohm','T':'C','P':'W/m'}
leg = [] # Storage for plots we want to legend
for alambre in sorted(alambres.keys()):
    model = sklearn.linear_model.LinearRegression()


    X = alambres[alambre]['mediciones'][x].reshape(-1, 1)
    Y = alambres[alambre]['mediciones'][y].reshape(-1, 1)
    model.fit(X,Y)


    x_label = d_unidades[x]
    y_label = d_unidades[y]

    plt.xlabel(x_label)
    plt.ylabel(y_label)
    dots, = plt.plot(X,Y,'8')
    line, = plt.plot(X, model.predict(X),'-')
    leg.append(line) # Choose what symbols will be represented in legend
plt.legend(leg, sorted(alambres.keys())) # Legend
plt.title('Heating wires')

plt.show()

If you want that both dots and lines were represented in legend, append to leg like this:

leg.append((dots, line))

Upvotes: 1

Related Questions