首页 > 解决方案 > python 2.7的暮光cmap

问题描述

我想在我的 2.7 python 版本中使用 twilight 或 twilight_shifted 颜色图,但它似乎只是 python 3?有什么方法可以手动添加吗?

标签: python-2.7matplotlibcolormap

解决方案


twilight仅在 python 3 的 matplotlib v3.0 中添加。但是我们可以在源代码中找到它被添加的地方,对其进行重新设计。

在下面的代码中,您只需要twilight通过以下链接从 github 上的 matplotlib 源中获取用于的数据。

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

_twilight_data = [ # data too long for stack overflow. get it from here:
                   # https://github.com/matplotlib/matplotlib/blob/f2116d82dfd6b82fe178230766d95ea9ac2b0c8c/lib/matplotlib/_cm_listed.py#L1288
                 ]

_twilight_shifted_data = (_twilight_data[len(_twilight_data)//2:] +
                          _twilight_data[:len(_twilight_data)//2])
_twilight_shifted_data.reverse()

cmaps = {}
for (name, data) in (('twilight', _twilight_data),
                     ('twilight_shifted', _twilight_shifted_data)):

    cmaps[name] = colors.ListedColormap(data, name=name)
    # generate reversed colormap
    name = name + '_r'
    cmaps[name] = colors.ListedColormap(list(reversed(data)), name=name)


fig, ax = plt.subplots()
p = ax.pcolormesh(np.arange(25).reshape(5, 5), cmap=cmaps['twilight'])
fig.colorbar(p, ax=ax)

plt.show()

用 , 和twilightcolormapstwilight_r创建一个dict 。twilight_shiftedtwilight_shifted_r

该脚本还生成此测试图像:

在此处输入图像描述


推荐阅读