pythonmatplotlibcolormap

Python matplotlib adjust colormap


This is what I want to create.

This is what I get.

This is the code I have written.

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm

x = np.linspace(-90, 90, 181)
y = np.linspace(-90, 90, 181)
x_grid, y_grid = np.meshgrid(x, y)
z = np.e**x_grid

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1, projection="3d")
ax.plot_surface(x_grid, y_grid, z, cmap=cm.rainbow)

I also tried to normalize z and the colormap.

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
import matplotlib as mpl

x = np.linspace(-90, 90, 181)
y = np.linspace(-90, 90, 181)
x_grid, y_grid = np.meshgrid(x, y)
z = np.e**x_grid
cmap = mpl.cm.rainbow
norm = mpl.colors.Normalize(vmin=0, vmax=1)

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1, projection="3d")
ax.plot_surface(x_grid, y_grid, z/np.max(z), norm=norm, cmap=cm.rainbow)

Question: How can I adjust the colormap to make it less discrete and more continuous for these simultaneously tiny and large values in z?


Solution

  • Your problem is related to the fact that you are working with exponential numbers, but you're using a linear colormap. For x=90 you have z=1.2e+39, reaaaally large.

    You were very close with your second attempt! I just changed 1 line in there, instead of

    norm = mpl.colors.Normalize(vmin=0, vmax=1)

    I used

    norm = mpl.colors.LogNorm()

    And the result I got was the following:

    enter image description here

    Now, you can tweak this as much as you like in order to get the colors you want :) Just don't forget that your colormap should be normalized in a logarithmic fashion, so that it counters the exponential behaviour of your function in this case.