Fomite
Fomite

Reputation: 2273

Adjusting the Line Colors in a Legend using matplotlib

I'm using the following code to generate a plot with a large number of overplotted lines in Python using matplotlib:

def a_run(n, t, s):
    xaxis = np.arange(t, dtype=float)
    #Scale x-axis by the step size
    for i in xaxis:
        xaxis[i]=(xaxis[i]*s)
    for j in range(n):
        result = a_solve(t,s)
        plt.plot(result[:,1], color = 'r', alpha=0.1)

def b_run(n, t, s):
    xaxis = np.arange(t, dtype=float)
    #Scale x-axis by the step size
    for i in xaxis:
        xaxis[i]=(xaxis[i]*s)
    for j in range(n):
        result = b_solve(t,s)
        plt.plot(result[:,1], color = 'b', alpha=0.1)

a_run(100, 300, 0.02)
b_run(100, 300, 0.02)   

plt.xlabel("Time")
plt.ylabel("P")
plt.legend(("A","B"), shadow=True, fancybox=True) Legend providing same color for both
plt.show()

This yields a plot like this:

enter image description here

The problem is the legend - because the lines are plotted with very high transparency, so are the legend lines, and that's very difficult to read. Additionally, it's plotting what I suspect are the "first two" lines, and both are red, when I need one red and one blue.

I can't see any means of adjusting the line colors in Matplotlib like I would in say, the R graphics libraries, but does anyone have a solid workaround?

Upvotes: 1

Views: 8849

Answers (2)

Thirsty
Thirsty

Reputation: 317

When I run your code I get an error but this should do the trick:

from matplotlib.lines import Line2D

custom_lines = [Line2D([0], [0], color='red', lw=2),
            Line2D([0], [0], color='blue', lw=2)]

plt.legend(custom_lines, ['A', 'B'])

reference: Composing Custom Legends

Upvotes: 3

Francesco Montesano
Francesco Montesano

Reputation: 8658

If you plot a lot of lines you should get better performances using LineCollection

import matplotlib.collections as mplcol
import matplotlib.colors as mplc

def a_run(n, t, s):
    xaxis = np.arange(t, dtype=float)
    #Scale x-axis by the step size
    for i in xaxis:
        xaxis[i]=(xaxis[i]*s)
    result = [a_solve(t,s)[:,1] for j in range(n)]
    lc = mplcol.LineCollection(result, colors=[mplc.to_rgba('r', alpha=0.1),]*n)
    plt.gca().add_collection(lc)
    return ls

[...]
lsa = a_run(...)
lsb = b_run(...)    
leg = plt.legend((lsa, lsb),("A","B"), shadow=True, fancybox=True)
#set alpha=1 in the legend
for l in leg.get_lines():
    l.set_alpha(1)
plt.draw()

I haven't tested the code itself, but I often do something similar to draw large sets of lines and have a legend with one line per each set plotted

Upvotes: 5

Related Questions