简体   繁体   English

使用matplotlib的颜色循环作为颜色图

[英]Using matplotlib's color cycle as a colormap

It's possible to set the color cycle to match an existing colormap, but this question is asking how to do the inverse: creating a qualitative colormap from the color cycle. 可以将颜色循环设置为与现有颜色映射匹配,但是这个问题是询问如何进行反转:从颜色循环创建定性颜色映射。

In my specific case, I've got a scatter plot with an associated array of integer class labels. 在我的具体情况下,我有一个带有相关的整数类标签数组的散点图。 My current plot looks like this: 我目前的情节如下:

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)

当前的散点图

As you can see, this doesn't do a great job of distinguishing the classes cleanly. 正如您所看到的,这并没有很好地区分干净的类。 Instead, I'd like to somehow plug in a colormap that matches the current color cycle, where label i corresponds to color_cycle[i] . 相反,我想以某种方式插入与当前颜色周期匹配的色彩映射,其中label i对应于color_cycle[i] If I have more classes than the color cycle has colors, that's fine, it should just wrap around like normal. 如果我有更多的类比颜色循环有颜色,那很好,它应该像往常一样环绕。

I don't think there is a public API for obtaining the current color cycle, but by mimicking set_prop_cycle you might define get_prop_cycle this way: 我认为没有用于获取当前颜色周期的公共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

Once you have the colors in prop_cycler , you can map c to colors in the color cycle: 获得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()

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM