python - Matplotlib:未对齐的颜色条刻度线?

标签 python matplotlib colorbar

我正在尝试使用定制的颜色图绘制 0-69 范围内的数据。这是一个例子:

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

colors = [(0.9, 0.9, 0.9),    # Value = 0
          (0.3, 0.3, 0.3),    # Value = 9
          (1.0, 0.4, 0.4),    # Value = 10
          (0.4, 0.0, 0.0),    # Value = 19
          (0.0, 0.7, 1.0),    # Value = 20
          (0.0, 0.1, 0.3),    # Value = 29
          (1.0, 1.0, 0.4),    # Value = 30
          (0.4, 0.4, 0.0),    # Value = 39
          (1.0, 0.4, 1.0),    # Value = 40
          (0.4, 0.0, 0.4),    # Value = 49
          (0.4, 1.0, 0.4),    # Value = 50
          (0.0, 0.4, 0.0),    # Value = 59
          (1.0, 0.3, 0.0),    # Value = 60
          (1.0, 0.8, 0.6)]    # Value = 69

# Create the values specified above
max_val = 69
values = [n for n in range(max_val + 1) if n % 10 == 0 or n % 10 == 9]

# Create colormap, first normalise values
values = [v / float(max_val) for v in values]
values_and_colors = [(v, c) for v, c in zip(values, colors)]
cmap = LinearSegmentedColormap.from_list('my_cmap', values_and_colors,
                                         N=max_val + 1)

# Create sample data in range 0-69
data = np.round(np.random.random((20, 20)) * max_val)

ax = plt.imshow(data, cmap=cmap, interpolation='nearest')
cb = plt.colorbar(ticks=range(0, max_val, 10))
plt.show()

enter image description here

我非常困惑为什么颜色条刻度与颜色渐变之间的明显分隔不对齐(每个颜色有 10 种颜色)。

我尝试将数据和 View 间隔设置为 [0, 69] 到 [0, 70]:

cb.locator.axis.set_view_interval(0, 70)
cb.locator.axis.set_data_interval(0, 70)
cb.update_ticks()

但这似乎没有做任何事情。

请问有人可以建议吗?

最佳答案

解决我的问题的最简单方法是在可映射的定义中设置vmax:

ax = plt.imshow(data, cmap=cmap, interpolation='nearest', vmax=max_val + 1)

它被设置为 max_val,因为 Colorbar 类在其 __init__ 中调用了 mappable.autoscale_None(),该调用设置 vmaxdata.max(),即 69。

认为我只是以错误方式使用LinearSegmentedColormap的受害者。我希望为特定颜色分配离散值,但与 LinearSegmentedColormap 关联的颜色条的显示假定连续数据,因此默认为 data.min()data.max(),即本例中为 0 和 69。

关于python - Matplotlib:未对齐的颜色条刻度线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39486999/

相关文章:

python - 使用python读取网络中所有系统的驱动数据

python - 像 Python 的 fakeweb 这样的库

python - 如何标记和更改 Seaborn kdeplot 轴的比例

python - 带颜色条的圆图

python - PyCharm 中类 'objects' 的未解析属性引用 'Foo'

python-3.x - 是否可以使用 seaborn 执行 "zoom inset"?

python - 绘制连音符列表的直方图 matplotlib

python-2.7 - 在 matplotlib 中更改颜色图的字体大小

R,scale_fill_stepsn() 中断和颜色错误

python - 你能在 Python 的核心类型上猴子补丁方法吗?