3

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.

ahajib
  • 12,838
  • 29
  • 79
  • 120

1 Answers1

4

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.

Sajjan Singh
  • 2,523
  • 2
  • 27
  • 34
  • Is it possible to add the labels next to the color bar on the right? I would like to have it labeled only at the extremes and ideally with some text. For example, the label '0' would be replaces by '$x=0$' and the label '1' by '$x=1$' – michalOut Jun 19 '19 at 19:47
  • I have found a solution in the meantime, so for anyone searching, visit [this answer][1] . By adding or removing elements in 'cmaps' one can adjust the number of different inputs. [1]: https://stackoverflow.com/questions/55501860/how-to-put-multiple-colormap-patches-in-a-matplotlib-legend – michalOut Jun 19 '19 at 21:08
  • You can set the tick labels of a colorbar, as this mpl demo shows: https://matplotlib.org/stable/gallery/ticks_and_spines/colorbar_tick_labelling_demo.html – jme Apr 05 '21 at 18:44