ahajib
ahajib

Reputation: 13510

Python matplotlib: Add legend for a colormap

I am new to matplotlib and I am trying to recreate a figure like the following which is a log-log figure:

enter image description here

I know that I have to use colormap to create such output based on my x and y values. What I can not figure is how to add the legend so it can calculates the values for the colormap variable (e.g. here called "Degree") dynamically. Here is what I've got for a sample figure so far:

from matplotlib import pyplot as plt

x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
y = [125, 32, 54, 253, 67, 87, 233, 56, 67]

color = [str(item/255.) for item in y]

plt.scatter(x, y, s=500, c=color)

plt.show()

Any help would be much appreciated.

Upvotes: 3

Views: 12054

Answers (1)

Sajjan Singh
Sajjan Singh

Reputation: 2553

You can assign an appropriate colormap for your plot, in this case a grayscale colormap:

x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
y = [125, 32, 54, 253, 67, 87, 233, 56, 67]

color = [item / 255.0 for item in y]
grayscale_map = plt.get_cmap('gray')

plt.figure()
plt.scatter(x, y, s = 500, c = color, cmap = grayscale_map)
plt.colorbar()
plt.show()

enter image description here

Note that I changed your color list to list of floats that will (presumably) range from 0 to 1.

Upvotes: 4

Related Questions