Custom colourmaps in matplotlib

2019-09-15 11:10发布

I'm trying to make my own colourmap in matplotlib but I can't seem to get it to work correctly, the colours it is outputting are not the ones I was expecting I've tried the other similar question's answers but to no avail, I can't seem to set my cdict tuples right.

I have a graph that has intensity going from 0 to 1. I want the zero intensity to have an RBG of (0,99,136), 0.5 intensity to have (159,161,97) and the 1 intensity to have (170,43,74)

This is what I am currently trying but I thing I have misunderstood how to use it.

from matplotlib.colors import LinearSegmentedColormap

cdict1 = {'blue':   ((0.0, 0.0, 0.0),
                    (0.5, 159/255, 159/255),
                    (1.0, 170/255, 170/255)),

         'green': ((0.0, 99/255, 99/255),
                   (0.5, 161/255, 161/255),
                   (1.0, 43/255, 43/255)),

         'red':  ((0.0, 136/255, 136/255),
                   (0.5, 97/255, 97/255),
                   (1.0, 74/255, 74/255))
         }

cm = LinearSegmentedColormap('cm', cdict1)

I'm implementing it in as so

plt.subplot(1, 2, 1)
matplotlib.rcParams.update({'font.size': 24})
plt.imshow(abs(store(0))**2, interpolation='none', extent=[-MaxMin, MaxMin, 0, N*dt], aspect=7, cmap=cm, vmin=0, vmax=1)
plt.xlabel(r'$x$')
plt.ylabel(r'$t$')
'cbar = plt.colorbar()'
plt.subplot(1, 2, 2)
plt.imshow(abs(store(4*x*x))**2, interpolation='none', extent=[-MaxMin, MaxMin, 0, N*dt], aspect=8, cmap=cm, vmin=0, vmax=1)
plt.xlabel(r'$x$')
plt.ylabel(r'$t$')
cbar = plt.colorbar()
cbar.set_label(r'$|\psi(x,t)|^{2}$', fontsize=24)
plt.show()

This is the output I currently get

Colourmap I get currently

And this is what I want to achieve Colourmap I want

1条回答
三岁会撩人
2楼-- · 2019-09-15 11:14

I think what you want can be achieved much easier than using this complicated dictionary.

Just create a 2D array which has in the first row the RGB values from the first color, in the second those from the middle color, and in the last row the values from the final color.
Then use the matplotlib.colors.LinearSegmentedColormap.from_list function to obtain a colormap.

import numpy as np
import matplotlib.colors

colors = np.array([(0,99,136), (159,161,97), (170,43,74)])/255.
cm = matplotlib.colors.LinearSegmentedColormap.from_list('cm', colors)

enter image description here

查看更多
登录 后发表回答