Home > OS >  Same Label displayed for Multiple Data Sets? (MatPlotLib, Python 3.9)
Same Label displayed for Multiple Data Sets? (MatPlotLib, Python 3.9)

Time:11-08

Is it possible to assign data sets to existing data labels with MatPlotLib?

Even if the data sets are assigned the same label name & color, in the actual resulting plot, in the legend they are separate, and have different colors. I'm using Python 3.9.

Let's say we have the following code:

import matplotlib.pyplot as plt

dataX = [[0, 1, 2], [0, 1, 2]]
dataY = [[0, 1, 2], [2, 1, 0]]

dataLabel = "Test Data"

for i in range(len(dataX)):
    plt.plot(dataX[i], dataY[i], label = dataLabel)

plt.legend(loc = 'best')

plt.show()

plt.close()

This results in the following plot: enter image description here

And what I want is for both of these data lines to be the same color, and have them both be labeled as the same "Test Data" label instance.

Is what I'm trying to achieve here even possible with MatPlotLib?

Thanks for reading my post, any help is appreciated!

CodePudding user response:

Define a color:

color = 'blue'

Set this color in plot function. Set label to first line only.

line = plt.plot(dataX[0], dataY[0], label=dataLabel, c=color)
for i in range(1, len(dataX)):
    plt.plot(dataX[i], dataY[i], c=color)

plt.legend(loc='best', handles=[line[0]])
  • Related