Home > Software engineering >  Force grayscale legend colors in scatterplot
Force grayscale legend colors in scatterplot

Time:05-23

I want to prepare a grayscale figure with multiple, overlapping scatter plots. A simplified version of my code is as follows:

for object in list_of_objects:
    plt.scatter(object.x,object.y,marker=object.marker,label=object.label)
plt.legend()
plt.show()

The problem is that the legend appears in non-grayscale color, so is there any way to force it to use grayscale colors? (i.e. a different grayscale color for the data of each object)

CodePudding user response:

Matplotlib If you need to use matplotlib, then here is a sample of how you can achieve this. Assuming there are 5 groups that you want to add here.

import numpy as np
import matplotlib.pyplot as plt

x = np.random.rand(100)
y = np.random.rand(100)
groups = [1, 2, 3, 4, 5] * 20

plt.scatter(x, y, c=groups, cmap='Greys')
plt.colorbar(ticks=[1, 2, 3, 4, 5])
plt.show()

Output graph:

Matplotlib

Seaborn If you are able to use seaborn, it is simpler... You can use palette = 'gray' and hue=<your group> to give it different shades of gray.

Sample code:

tips = sns.load_dataset("tips")
sns.scatterplot(data=tips, x="total_bill", y="tip", hue="size", palette="gray")

Will give this pic

scatter plot

  • Related