How to define color code with absolute values ​​using matplotlib

I use the following script to build:

import matplotlib

import matplotlib.pyplot as plt
import numpy as np
import pylab as pl
import math
import matplotlib as mpl
from matplotlib.ticker import MultipleLocator
from matplotlib.colors import LinearSegmentedColormap

cdict1 = {'red':   ((0.0, 1.0, 1.0),
                   (0.4, 1.0, 1.0),
                   (0.7, 0.0, 0.0),
                   (1.0, 0.0, 0.0)),

         'green': ((0.0, 1.0, 1.0),
                   (0.1, 0.0, 0.0),
                   (1.0, 0.0, 0.0)),

         'blue':   ((0.0, 1.0, 1.0),
                   (0.1, 0.0, 0.0),
                   (0.4, 0.0, 0.0),
                   (1.0, 1.0, 1.0))
        }

white_blue_red = LinearSegmentedColormap('WhiteBlueRed', cdict1)
plt.register_cmap(cmap=white_blue_red)

x = np.loadtxt('data.dat',
                 unpack=True)

plt.scatter(x[0], x[1], marker='.', s=3, linewidths=0, c=x[3], cmap= \
            plt.get_cmap('WhiteBlueRed')) # plt.cm.bwr  
plt.colorbar()

plt.show()

The color scheme I defined uses relative values ​​(0 is the minimum value of the maximum value of function 1). the problem is that I want to use this code to build hundreds of different files, and I want each plot to have the same color. Is it possible to define color maps with absolute values? This will solve my problem.

+4
source share
1 answer

The key in this case is this norm, not the color palette.

. norm 0-1.

Normalize, vmin vmax kwargs, .

, .

, norm, cmap : matplotlib.colors.from_levels_and_colors BoundaryNorm LinearSegmentedColormap:

:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors

data1 = 3 * np.random.random((10, 10))
data2 = 5 * np.random.random((10, 10))

levels = [0, 1, 2, 3, 4, 5]
colors = ['red', 'brown', 'yellow', 'green', 'blue']
cmap, norm = matplotlib.colors.from_levels_and_colors(levels, colors)

fig, axes = plt.subplots(ncols=2)
for ax, dat in zip(axes, [data1, data2]):
    im = ax.imshow(dat, cmap=cmap, norm=norm, interpolation='none')
    fig.colorbar(im, ax=ax, orientation='horizontal')
plt.show()

enter image description here

, .

colormap , vmin vmax, Normalize norm .

, :

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap

data1 = 3 * np.random.random((10, 10))
data2 = 5 * np.random.random((10, 10))

colors = ['red', 'brown', 'yellow', 'green', 'blue']
cmap = LinearSegmentedColormap.from_list('name', colors)
norm = plt.Normalize(0, 5)

fig, axes = plt.subplots(ncols=2)
for ax, dat in zip(axes, [data1, data2]):
    im = ax.imshow(dat, cmap=cmap, norm=norm, interpolation='none')
    fig.colorbar(im, ax=ax, orientation='horizontal')
plt.show()

enter image description here

+6

Source: https://habr.com/ru/post/1608878/


All Articles