Matplotlib半色轴

时间:2014-07-14 21:24:45

标签: python matplotlib colorbar

我正在使用matplotlib制作一些情节,我遇到了一些我需要帮助的困难。

问题1)为了保持一致的色彩方案,我只需要使用一半的色轴。只有正值,所以我希望零值为绿色,中间值为黄色,最高值为红色。与此最匹配的配色方案是gist_rainbow_r,但我只想要它的上半部分。

问题2)我似乎无法弄清楚如何在图表的右侧显示颜色条以显示或如何让它标记轴。

如果有帮助,我使用最新版本的Anaconda和matplotlib的Latext版本

cmap = plt.get_cmap('gist_rainbow_r')
edosfig2 = plt.figure(2)
edossub2 = edosfig.add_subplot(1,1,1)
edossub2 = plt.contourf(eVec,kints,smallEDOS,cmap=cmap)
edosfig2.show()

1 个答案:

答案 0 :(得分:11)

如果您有一组特定的颜色要用于色彩映射,则可以根据这些颜色进行构建。例如:

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

cmap = LinearSegmentedColormap.from_list('name', ['green', 'yellow', 'red'])

# Generate some data similar to yours
y, x = np.mgrid[-200:1900, -300:2000]
z = np.cos(np.hypot(x, y) / 100) + 1

fig, ax = plt.subplots()

cax = ax.contourf(x, y, z, cmap=cmap)
cbar = fig.colorbar(cax)
cbar.set_label('Z-Values')

plt.show()

enter image description here


但是,如果你只是想要一些特别复杂的色彩图的上半部分,你可以通过评估你感兴趣的范围内的色彩图来复制它的一部分。例如,如果你想要“顶部”的一半,你要从0.5到1进行评估:

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

# Evaluate an existing colormap from 0.5 (midpoint) to 1 (upper end)
cmap = plt.get_cmap('gist_earth')
colors = cmap(np.linspace(0.5, 1, cmap.N // 2))

# Create a new colormap from those colors
cmap2 = LinearSegmentedColormap.from_list('Upper Half', colors)

y, x = np.mgrid[-200:1900, -300:2000]
z = np.cos(np.hypot(x, y) / 100) + 1

fig, axes = plt.subplots(ncols=2)
for ax, cmap in zip(axes.flat, [cmap, cmap2]):
    cax = ax.imshow(z, cmap=cmap, origin='lower',
                    extent=[x.min(), x.max(), y.min(), y.max()])
    cbar = fig.colorbar(cax, ax=ax, orientation='horizontal')
    cbar.set_label(cmap.name)

plt.show()

enter image description here