本文整理汇总了Python中matplotlib.pyplot.register_cmap方法的典型用法代码示例。如果您正苦于以下问题:Python pyplot.register_cmap方法的具体用法?Python pyplot.register_cmap怎么用?Python pyplot.register_cmap使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类matplotlib.pyplot
的用法示例。
在下文中一共展示了pyplot.register_cmap方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: colors2cmap
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import register_cmap [as 别名]
def colors2cmap(*args, name=None):
"""Create a colormap from a list of given colors.
Parameters:
*args: Arbitrary number of colors (Named color, HEX or RGB).
name (str): Name with which the colormap is registered.
Returns:
LinearSegmentedColormap.
Examples:
>>> colors2cmap('darkorange', 'white', 'darkgreen', name='test')
"""
if len(args) < 2:
raise Exception("Give at least two colors.")
cmap_data = [_to_hex(c) for c in args]
cmap = colors.LinearSegmentedColormap.from_list(name, cmap_data)
plt.register_cmap(name, cmap)
return cmap
示例2: test_cmap_from_txt
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import register_cmap [as 别名]
def test_cmap_from_txt(self):
"""Import colormap from txt file."""
viridis = plt.get_cmap('viridis')
cmap = colors.cmap_from_txt(os.path.join(self.ref_dir, 'viridis.txt'))
plt.register_cmap(cmap=viridis) # Register original viridis.
idx = np.linspace(0, 1, 256)
assert np.allclose(viridis(idx), cmap(idx), atol=0.001)
示例3: test_cmap_from_act
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import register_cmap [as 别名]
def test_cmap_from_act(self):
"""Import colormap from act file."""
viridis = plt.get_cmap('viridis')
cmap = colors.cmap_from_act(os.path.join(self.ref_dir, 'viridis.act'))
plt.register_cmap(cmap=viridis) # Register original viridis.
idx = np.linspace(0, 1, 256)
assert np.allclose(viridis(idx), cmap(idx), atol=0.004)
示例4: cmap_from_act
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import register_cmap [as 别名]
def cmap_from_act(file, name=None):
"""Import colormap from Adobe Color Table file.
Parameters:
file (str): Path to act file.
name (str): Colormap name. Defaults to filename without extension.
Returns:
LinearSegmentedColormap.
"""
# Extract colormap name from filename.
if name is None:
name = os.path.splitext(os.path.basename(file))[0]
# Read binary file and determine number of colors
rgb = np.fromfile(file, dtype=np.uint8)
if rgb.shape[0] >= 770:
ncolors = rgb[768] * 2**8 + rgb[769]
else:
ncolors = 256
colors = rgb[:ncolors*3].reshape(ncolors, 3) / 255
# Create and register colormap...
cmap = LinearSegmentedColormap.from_list(name, colors, N=ncolors)
plt.register_cmap(cmap=cmap) # Register colormap.
# ... and the reversed colormap.
cmap_r = LinearSegmentedColormap.from_list(
name + '_r', np.flipud(colors), N=ncolors)
plt.register_cmap(cmap=cmap_r)
return cmap
示例5: cmap_from_txt
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import register_cmap [as 别名]
def cmap_from_txt(file, name=None, N=-1, comments='%'):
"""Import colormap from txt file.
Reads colormap data (RGB/RGBA) from an ASCII file.
Values have to be given in [0, 1] range.
Parameters:
file (str): Path to txt file.
name (str): Colormap name. Defaults to filename without extension.
N (int): Number of colors.
``-1`` means all colors (i.e., the complete file).
comments (str): Character to start comments with.
Returns:
LinearSegmentedColormap.
"""
# Extract colormap name from filename.
if name is None:
name = os.path.splitext(os.path.basename(file))[0]
# Read binary file and determine number of colors
rgb = np.genfromtxt(file, comments=comments)
if N == -1:
N = np.shape(rgb)[0]
if np.min(rgb) < 0 or np.max(rgb) > 1:
raise Exception('RGB value out of range: [0, 1].')
# Create and register colormap...
cmap = LinearSegmentedColormap.from_list(name, rgb, N=N)
plt.register_cmap(cmap=cmap)
# ... and the reversed colormap.
cmap_r = LinearSegmentedColormap.from_list(
name + '_r', np.flipud(rgb), N=N)
plt.register_cmap(cmap=cmap_r)
return cmap
示例6: make_im_png
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import register_cmap [as 别名]
def make_im_png(data, pngfile, cmap, title, vmin=None, vmax=None, cbar=True):
"""
Make png image.
cmap can be 'insar'. To wrap data, np.angle(np.exp(1j*x/cycle)*cycle)
"""
if cmap=='insar':
cdict = tools_lib.cmap_insar()
plt.register_cmap(name='insar',data=cdict)
length, width = data.shape
figsizex = 8
xmergin = 2 if cbar else 0
figsizey = int((figsizex-xmergin)*(length/width))+1
### Plot
fig, ax = plt.subplots(1, 1, figsize=(figsizex, figsizey))
plt.tight_layout()
im = ax.imshow(data, vmin=vmin, vmax=vmax, cmap=cmap)
ax.set_xticklabels([])
ax.set_yticklabels([])
ax.set_title(title)
if cbar: fig.colorbar(im)
plt.savefig(pngfile)
plt.close()
return
#%%
示例7: make_3im_png
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import register_cmap [as 别名]
def make_3im_png(data3, pngfile, cmap, title3, vmin=None, vmax=None, cbar=True):
"""
Make png with 3 images for comparison.
data3 and title3 must be list with 3 elements.
cmap can be 'insar'. To wrap data, np.angle(np.exp(1j*x/cycle)*cycle)
"""
### Plot setting
if cmap=='insar':
cdict = tools_lib.cmap_insar()
plt.register_cmap(name='insar',data=cdict)
length, width = data3[0].shape
figsizex = 12
xmergin = 4 if cbar else 0
figsizey = int((figsizex-xmergin)/3*length/width)+2
fig = plt.figure(figsize = (figsizex, figsizey))
for i in range(3):
ax = fig.add_subplot(1, 3, i+1) #index start from 1
im = ax.imshow(data3[i], vmin=vmin, vmax=vmax, cmap=cmap)
ax.set_title(title3[i])
ax.set_xticklabels([])
ax.set_yticklabels([])
if cbar: fig.colorbar(im, ax=ax)
plt.tight_layout()
plt.savefig(pngfile)
plt.close()
return
#%%
示例8: shiftedColorMap
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import register_cmap [as 别名]
def shiftedColorMap(cmap, start=0, midpoint=0.5, stop=1.0, name="shiftedcmap"):
"""Function to offset the "center" of a colormap. Useful for data with a negative
min and positive max and you want the middle of the colormap's dynamic range to be
at zero.
Source:
http://stackoverflow.com/questions/7404116/defining-the-midpoint-of-a-colormap-in-matplotlib
Parameters
----------
cmap : str
The matplotlib colormap to be altered
start : any number
Offset from lowest point in the colormap's range. Defaults to 0.0 (no lower
offset). Should be between 0.0 and `midpoint`.
midpoint : any number between 0.0 and 1.0
The new center of the colormap. Defaults to 0.5 (no shift). In general, this
should be 1 - vmax/(vmax + abs(vmin)). For example if your data range from
-15.0 to +5.0 and you want the center of the colormap at 0.0, `midpoint` should
be set to 1 - 5/(5 + 15)) or 0.75.
stop : any number between `midpoint` and 1.0
Offset from highets point in the colormap's range. Defaults to 1.0 (no upper
offset).
Returns
-------
matplotlib.cmap
The colormap with its centre shifted to the midpoint value.
"""
cdict = {"red": [], "green": [], "blue": [], "alpha": []}
# regular index to compute the colors
reg_index = np.linspace(start, stop, 257)
# shifted index to match the data
shift_index = np.hstack(
[
np.linspace(0.0, midpoint, 128, endpoint=False),
np.linspace(midpoint, 1.0, 129, endpoint=True),
]
)
for ri, si in zip(reg_index, shift_index):
r, g, b, a = cmap(ri)
cdict["red"].append((si, r, r))
cdict["green"].append((si, g, g))
cdict["blue"].append((si, b, b))
cdict["alpha"].append((si, a, a))
newcmap = matplotlib.colors.LinearSegmentedColormap(name, cdict)
plt.register_cmap(cmap=newcmap)
return newcmap
示例9: shiftedColorMap
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import register_cmap [as 别名]
def shiftedColorMap(cmap, start=0.0, midpoint=0.75, stop=1.0, name='shiftedcmap'):
'''
Function to offset the "center" of a colormap. Useful for
data with a negative min and positive max and you want the
middle of the colormap's dynamic range to be at zero
Input
-----
cmap : The matplotlib colormap to be altered
start : Offset from lowest point in the colormap's range.
Defaults to 0.0 (no lower ofset). Should be between
0.0 and 1.0.
midpoint : The new center of the colormap. Defaults to
0.5 (no shift). Should be between 0.0 and 1.0. In
general, this should be 1 - vmax/(vmax + abs(vmin))
For example if your data range from -15.0 to +5.0 and
you want the center of the colormap at 0.0, `midpoint`
should be set to 1 - 5/(5 + 15)) or 0.75
stop : Offset from highets point in the colormap's range.
Defaults to 1.0 (no upper ofset). Should be between
0.0 and 1.0.
'''
cdict = {
'red': [],
'green': [],
'blue': [],
'alpha': []
}
# regular index to compute the colors
reg_index = np.linspace(start, stop, 257)
# shifted index to match the data
shift_index = np.hstack([
np.linspace(0.0, midpoint, 128, endpoint=False),
np.linspace(midpoint, 1.0, 129, endpoint=True)
])
for ri, si in zip(reg_index, shift_index):
r, g, b, a = cmap(ri)
cdict['red'].append((si, r, r))
cdict['green'].append((si, g, g))
cdict['blue'].append((si, b, b))
cdict['alpha'].append((si, a, a))
newcmap = mcolors.LinearSegmentedColormap(name, cdict)
plt.register_cmap(cmap=newcmap)
return newcmap
示例10: rainbowgram
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import register_cmap [as 别名]
def rainbowgram(path,
ax,
peak=70.0,
use_cqt=False,
n_fft=1024,
hop_length=256,
sr=22050,
over_sample=4,
res_factor=0.8,
octaves=5,
notes_per_octave=10):
audio = librosa.load(path, sr=sr)[0]
if use_cqt:
C = librosa.cqt(audio,
sr=sr,
hop_length=hop_length,
bins_per_octave=int(notes_per_octave * over_sample),
n_bins=int(octaves * notes_per_octave * over_sample),
filter_scale=res_factor,
fmin=librosa.note_to_hz('C2'))
else:
C = librosa.stft(
audio,
n_fft=n_fft,
win_length=n_fft,
hop_length=hop_length,
center=True)
mag, phase = librosa.core.magphase(C)
phase_angle = np.angle(phase)
phase_unwrapped = np.unwrap(phase_angle)
dphase = phase_unwrapped[:, 1:] - phase_unwrapped[:, :-1]
dphase = np.concatenate([phase_unwrapped[:, 0:1], dphase], axis=1) / np.pi
mag = (librosa.logamplitude(
mag**2, amin=1e-13, top_db=peak, ref_power=np.max) / peak) + 1
cdict = {
'red': ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0)),
'green': ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0)),
'blue': ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0)),
'alpha': ((0.0, 1.0, 1.0), (1.0, 0.0, 0.0))
}
my_mask = matplotlib.colors.LinearSegmentedColormap('MyMask', cdict)
plt.register_cmap(cmap=my_mask)
ax.matshow(dphase[::-1, :], cmap=plt.cm.rainbow)
ax.matshow(mag[::-1, :], cmap=my_mask)
示例11: shiftedColorMap
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import register_cmap [as 别名]
def shiftedColorMap(cmap, start=0, midpoint=0.5, stop=1.0, name='shiftedcmap'):
'''
This function is from: https://stackoverflow.com/a/20528097/8500469
Function to offset the "center" of a colormap. Useful for
data with a negative min and positive max and you want the
middle of the colormap's dynamic range to be at zero
Input
-----
cmap : The matplotlib colormap to be altered
start : Offset from lowest point in the colormap's range.
Defaults to 0.0 (no lower ofset). Should be between
0.0 and `midpoint`.
midpoint : The new center of the colormap. Defaults to
0.5 (no shift). Should be between 0.0 and 1.0. In
general, this should be 1 - vmax/(vmax + abs(vmin))
For example if your data range from -15.0 to +5.0 and
you want the center of the colormap at 0.0, `midpoint`
should be set to 1 - 5/(5 + 15)) or 0.75
stop : Offset from highets point in the colormap's range.
Defaults to 1.0 (no upper ofset). Should be between
`midpoint` and 1.0.
'''
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
cdict = {
'red': [],
'green': [],
'blue': [],
'alpha': []
}
# regular index to compute the colors
reg_index = np.linspace(start, stop, 257)
# shifted index to match the data
shift_index = np.hstack([
np.linspace(0.0, midpoint, 128, endpoint=False),
np.linspace(midpoint, 1.0, 129, endpoint=True)
])
for ri, si in zip(reg_index, shift_index):
r, g, b, a = cmap(ri)
cdict['red'].append((si, r, r))
cdict['green'].append((si, g, g))
cdict['blue'].append((si, b, b))
cdict['alpha'].append((si, a, a))
newcmap = matplotlib.colors.LinearSegmentedColormap(name, cdict)
plt.register_cmap(cmap=newcmap)
return newcmap
示例12: make_loop_png
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import register_cmap [as 别名]
def make_loop_png(ifgd12, ifgd23, ifgd13, unw12, unw23, unw13, loop_ph, loop_pngdir):
### Load color map for InSAR
cdict = tools_lib.cmap_insar()
plt.register_cmap(name='insar', data=cdict)
rms = np.sqrt(np.nanmean(loop_ph**2))
### Settings
imd1 = ifgd12[:8]
imd2 = ifgd23[:8]
imd3 = ifgd23[-8:]
pngname = os.path.join(loop_pngdir, imd1+'_'+imd2+'_'+imd3+'_loop.png')
cycle = 3 # 2pi*3/cycle
titles = [ifgd12, ifgd23, ifgd13]
data = [unw12, unw23, unw13]
length, width = unw12.shape
if length > width:
figsize_y = 10
figsize_x = int((figsize_y-1)*width/length)
if figsize_x < 5: figsize_x = 5
else:
figsize_x = 10
figsize_y = int(figsize_x*length/width+1)
if figsize_y < 3: figsize_y = 3
### Plot
fig = plt.figure(figsize = (figsize_x, figsize_y))
## 3 ifgs
for i in range(3):
data_wrapped = np.angle(np.exp(1j*(data[i]/cycle))*cycle)
ax = fig.add_subplot(2, 2, i+1) #index start from 1
ax.imshow(data_wrapped, vmin=-np.pi, vmax=+np.pi, cmap='insar')
ax.set_title('{}'.format(titles[i]))
ax.set_xticklabels([])
ax.set_yticklabels([])
## loop phase
ax = fig.add_subplot(2, 2, 4) #index start from 1
ax.imshow(loop_ph, vmin=-np.pi, vmax=+np.pi, cmap=SCM.vik)
ax.set_title('Loop phase (RMS={:.2f}rad)'.format(rms))
ax.set_xticklabels([])
ax.set_yticklabels([])
plt.tight_layout()
plt.savefig(pngname)
plt.close()