【发布时间】:2019-12-12 23:55:36
【问题描述】:
我想在我的 2.7 python 版本中使用 twilight 或 twilight_shifted 颜色图,但它似乎只适用于 python 3?有什么方法可以手动添加吗?
【问题讨论】:
标签: python-2.7 matplotlib colormap
我想在我的 2.7 python 版本中使用 twilight 或 twilight_shifted 颜色图,但它似乎只适用于 python 3?有什么方法可以手动添加吗?
【问题讨论】:
标签: python-2.7 matplotlib colormap
twilight 被添加到 matplotlib v3.0 中,它只是 python 3。但是我们可以在源代码中找到它被添加的地方都重新设计它。
在下面的代码中,您只需要从 github 上的 matplotlib 源中获取用于 twilight 的数据,方法是遵循此 link。
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()
这会创建一个带有 twilight、twilight_r、twilight_shifted 和 twilight_shifted_r 颜色映射的字典。
该脚本还会生成此测试图像:
【讨论】:
您可以从当前版本中获取 _cm_listed.py 文件并将其复制到您的 matplotlib 2.2.3 文件夹中。由于该文件与版本无关,这应该会直接为您提供额外的颜色图。
【讨论】: