Home > Software engineering >  How to make two lines use the same color and legend label in matplotlib?
How to make two lines use the same color and legend label in matplotlib?

Time:01-05

let's say I have two sets of data to plot, x1 vs. y1, and x2 vs. y2. Where we can take the x variables as vectors of time, and y a matrix with the same number of rows as x, and 5 columns, each column being its individual line:

for i in range(5):
    plt.plot(x1,y1[:,i],x2,y2[:,i],label=labels[i])
plt.legend()

This results in each line being given a different color, and an individual label, where each label is repeated once. How can I have the data on each iteration in the for loop being plotted with the same color, and juts one label?

Thanks!

CodePudding user response:

There are many ways to accomplish what you are asking.

Here is a simple approach which uses the automatic coloring scheme for the first line, and extracts its color to asign to the second line. Only the first line gets a label for the legend.

for i in range(5):
    line, = plt.plot(x1, y1[i, :], label=f'label {i}')
    plt.plot(x2, y2[i, :], color=line.get_color())
plt.legend()

CodePudding user response:

You can define colours by the c parameter in plt.plot. If you set this all to the same colour, every line will be the same colour:

c = "#000000"
for i in range(5):
    plt.plot(x1,y1[:,i],x2,y2[:,i],label=labels[i], c=c)
plt.legend()

Now for the labels, in order to have 1 label for all lines, you can only just label one line. This can be done by:

c = "#000000"
label = "Same label"
for i in range(5):
    if i == 0:
        plt.plot(x1,y1[:,i],x2,y2[:,i],label=label, c=c)
    else:
        plt.plot(x1,y1[:,i],x2,y2[:,i], c=c)
plt.legend()

This should make all lines the same colour (black in this case) and the label Same label only occurs once in the legend.

  • Related