我怎么能得到不同的馅饼

2024-09-30 10:40:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我怎样才能得到不同的饼图颜色?我有一个大约20个类别的数据集,它可能会更大。当我创建一个饼图时,一些楔子有相同的颜色,所以我想知道有没有一种方法可以让我的饼图楔形图中的所有颜色都不同? 谢谢!在


Tags: 数据方法颜色类别楔形楔子
1条回答
网友
1楼 · 发布于 2024-09-30 10:40:13

20种颜色正是通过matplotlib中的分类/定性颜色映射所能达到的极限。当前matplotlib提供tab20tab20btab20c颜色映射。在

import matplotlib.pyplot as plt
import numpy as np

data = np.random.randint(50,200, size=20)

fig = plt.figure()

with plt.style.context({"axes.prop_cycle" : plt.cycler("color", plt.cm.tab20.colors)}):
    ax = fig.add_subplot(121, aspect="equal")
    ax.pie(data)

with plt.style.context({"axes.prop_cycle" : plt.cycler("color", plt.cm.tab20c.colors)}):
    ax2 = fig.add_subplot(122, aspect="equal")
    ax2.pie(data)

plt.show()

{a1}

当然,对于更多的颜色,也可以使用different colormaps,但这些颜色通常会导致相邻的颜色非常相似。E、 对于有30种不同颜色的饼图,我们可以使用nipy_spectral或{}颜色图。在

^{pr2}$

enter image description here

所以你可以增加另一个维度。从任何颜色贴图中选择一些颜色,并为每个颜色创建不同的亮度级别。这基本上显示在this answer中。在这里,为了得到例如30种不同的颜色,我们可以选择6种颜色,每5种亮度等级。在

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

def categorical_cmap(nc, nsc, cmap="tab10", continuous=False):
    if nc > plt.get_cmap(cmap).N:
        raise ValueError("Too many categories for colormap.")
    if continuous:
        ccolors = plt.get_cmap(cmap)(np.linspace(0,1,nc))
    else:
        ccolors = plt.get_cmap(cmap)(np.arange(nc, dtype=int))
    cols = np.zeros((nc*nsc, 3))
    for i, c in enumerate(ccolors):
        chsv = matplotlib.colors.rgb_to_hsv(c[:3])
        arhsv = np.tile(chsv,nsc).reshape(nsc,3)
        arhsv[:,1] = np.linspace(chsv[1],0.25,nsc)
        arhsv[:,2] = np.linspace(chsv[2],1,nsc)
        rgb = matplotlib.colors.hsv_to_rgb(arhsv)
        cols[i*nsc:(i+1)*nsc,:] = rgb       
    cmap = matplotlib.colors.ListedColormap(cols)
    return cmap

data = np.random.randint(50,200, size=30)

fig = plt.figure()

cc = plt.cycler("color", categorical_cmap(6, 5, cmap="tab10").colors)
with plt.style.context({"axes.prop_cycle" : cc}):
    ax = fig.add_subplot(121, aspect="equal")
    ax.pie(data)

cc = plt.cycler("color", 
                categorical_cmap(6, 5, cmap="gist_rainbow", continuous=True).colors)
with plt.style.context({"axes.prop_cycle" : cc}):
    ax2 = fig.add_subplot(122, aspect="equal")
    ax2.pie(data)

plt.show()

enter image description here

相关问题 更多 >

    热门问题