Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reading a tiff file using matplotlib and plotting it in a logarithmic scale [duplicate]

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.

like image 264
Cokes Avatar asked Jan 17 '26 04:01

Cokes


2 Answers

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
like image 131
tacaswell Avatar answered Jan 19 '26 18:01

tacaswell


The answer by tacaswell is entirely correct, but there's a slightly simpler call signature to accomplish the same thing: You can simply pass norm='log'. For example:

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

This is mentioned in the docs for scatter, and also works for other color-mapped plots such as pcolormesh.

(I realize this is mentioned in a comment, but I overlooked that comment the first time I found this answer. I think this merits its own Answer.)

like image 25
Joris Avatar answered Jan 19 '26 18:01

Joris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!