A logarithmic colorbar in matplotlib scatter plot
Asked Answered
D

1

102

I would like to make the colors of the points on the scatter plot correspond to the value of the void fraction, but on a logarithmic scale to amplify differences. I did this, but now when I do plt.colorbar(), it displays the log of the void fraction, when I really want the actual void fraction. How can I make a log scale on the colorbar with the appropriate labels of the void fraction, which belongs to [0.00001,1]?

Here is an image of the plot I have now, but the void fraction colorbar is not appropriately labeled to correspond to the true void fraction, instead of the log of it.

current plot

fig = plt.figure()
plt.scatter(x,y,edgecolors='none',s=marker_size,c=np.log(void_fraction))
plt.colorbar()
plt.title('Colorbar: void fraction')

Thanks for your help.

Deprave answered 19/6, 2013 at 20:56 Comment(0)
A
133

There is now a section of the documentation describing how color mapping and normalization works

The way that matplotlib does color mapping is in two steps, first a Normalize function (wrapped up by the sub-classes of matplotlib.colors.Normalize) which maps the data you hand in to [0, 1]. The second step maps values in [0,1] -> RGBA space.

You just need to use the LogNorm normalization class, passed in with the norm kwarg.

plt.scatter(x,y,edgecolors='none',s=marker_size,c=void_fraction,
                norm=matplotlib.colors.LogNorm())

When you want to scale/tweak data for plotting, it is better to let matplotlib do the transformations than to do it your self.

  • Normalize doc
  • LogNorm doc
  • matplotlib.color doc
Abscise answered 19/6, 2013 at 22:6 Comment(4)
The result is in Fig 2. pubs.rsc.org/en/content/articlehtml/2014/cp/c3cp55039g I added Stack Overflow in the acknowledgements!Deprave
Thank you! IF only the docs hinted at where to look. There are all these fantastic functions with fantastic parameters offering fantastic possibilities but nothing on how to use them.Mailemailed
Please suggest edits to the docs based on what you now understandAbscise
More easily, you could just pass norm="log".Immethodical

© 2022 - 2024 — McMap. All rights reserved.