使用matplotlib的颜色循环作为一种颜色映射。

3

可以将颜色循环设置为匹配现有的色图,但是这个问题要求如何做相反的操作:从颜色循环创建定性色图。

在我的特定情况下,我有一个带有相关整数类标签的散点图。我的当前绘图如下:

x,y = np.random.normal(size=(2,250))
theta = np.arctan2(y,x)
c = np.digitize(theta, np.histogram(theta)[1])
plt.scatter(x,y,c=c)

当前散点图

从图中可以看出,它并不能很好地清晰区分不同的类别。相反,我想要以某种方式插入一个与当前颜色循环匹配的颜色映射表,其中标签 i 对应 color_cycle[i]。如果我的类别多于颜色循环中的颜色,那么没关系,它应该像平常一样循环回来。

1个回答

1

我认为目前没有公共API可以获取当前的颜色循环,但是通过模拟set_prop_cycle,您可以这样定义get_prop_cycle

rcParams = plt.matplotlib.rcParams
def get_prop_cycle():
    prop_cycler = rcParams['axes.prop_cycle']
    if prop_cycler is None and 'axes.color_cycle' in rcParams:
        clist = rcParams['axes.color_cycle']
        prop_cycler = cycler('color', clist)
    return prop_cycler

一旦您在 prop_cycler 中有了颜色,您可以将 c 映射到颜色循环中的颜色:

colors = [item['color'] for item in get_prop_cycle()]
c = np.take(colors, c, mode='wrap')

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.rcsetup import cycler

np.random.seed(2016)

rcParams = plt.matplotlib.rcParams
def get_prop_cycle():
    prop_cycler = rcParams['axes.prop_cycle']
    if prop_cycler is None and 'axes.color_cycle' in rcParams:
        clist = rcParams['axes.color_cycle']
        prop_cycler = cycler('color', clist)
    return prop_cycler

fig, ax = plt.subplots(nrows=2)
x,y = np.random.normal(size=(2,250))
theta = np.arctan2(y,x)
c = np.digitize(theta, np.histogram(theta)[1])

ax[0].scatter(x,y,c=c)
ax[0].set_title('using default colormap')

colors = [item['color'] for item in get_prop_cycle()]
c = np.take(colors, c, mode='wrap')

ax[1].scatter(x,y,c=c)
ax[1].set_title('using color cycle')
plt.show()

enter image description here


谢谢,这正是我需要的!我发现使用c = np.take(colors, c, mode='wrap')比循环/切片组合更简单。 - perimosocordiae
@perimosocordiae: 感谢您的巨大改进。 - unutbu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接