Matplotlib set legend color

I am creating a plot using matplot lib to plot many points (~ several thousand) by doing the following:

labels = []
for item in items:
        label = item[0]
        labels.append(label)
        plt.plot(item[1][0], item[1][1], 'ro', c = colors[item], label = str(label))

      

And then creating the legend by doing:

plt.legend([str(x) for x in np.unique(labels)])

However, for each label in the legend, the corresponding color is the same (not the color in the graph). Is there a way to manually set the color for the legend.

I have provided a rough graph to illustrate the problem. enter image description here

- EDIT-- Just a call plt.legend()

suggested by some doesn't seem to solve the problem for me, it adds an entry for each point. See image below for example output: enter image description here

+3


source to share


2 answers


This should work:

labels = []
for item in items:
    label = item[0]
    plt.plot(item[1][0], item[1][1], 'o', c=colors[item], label=str(label))
plt.legend()

      



If you specify labels directly when creating the executor (in a call plot

), you can simply call plt.legend()

without arguments. It will walk through the artists on the current axis and use their labels. Thus, the colors in the legend will match the colors in the graph.

+2


source


You can also create fake line markers and use them as legend entries:

markers = [plt.Line2D([0,0],[0,0], color=color[item], marker='o', linestyle='') for item in np.unique(items)]
plt.legend(markers, np.unique(labels), numpoints=1)

      



You can see a complete example in this answer .

Please note that I have not tested this and you may need to tweak np.unique(items)

to your actual dataset. color

considered a dictionary with colors for your items.

0


source







All Articles