我如何使用正确的cmap np.array,使内部颜色与matplotlib中嵌套饼图中的外部颜色阴影相对应?
我尝试使用不同的cmap数组,但是我不明白如何将数组转换为cmap颜色。
import numpy as np
import matplotlib.pyplot as plt
y =np.array([17, 16, 10, 8 ,6, 5, 5, 4, 3, 17 ,2 ,1, 1, 3, 2 ])
x = np.array([74 ,21 ,5])
fig, ax = plt.subplots()
size = 0.3
cmap = plt.get_cmap("tab20c")
outer_colors = cmap(np.arange(3)*4)
inner_colors = cmap(np.array([1, 2, 5, 6, 9, 10]))
ax.pie(x, radius=1, colors=outer_colors,
wedgeprops=dict(width=size, edgecolor='w'))
ax.pie(y, radius=1-size, colors=inner_colors,
wedgeprops=dict(width=size, edgecolor='w'))
ax.set(aspect="equal", title='Pie plot with `ax.pie`')
plt.show()
我希望内部颜色是外部颜色(绿色,蓝色和橙色)的阴影,但是我不知道如何相应地进行更改。
谢谢!
答案 0 :(得分:2)
tab20c
色彩表的每个色调有4个阴影。因此,不可能将其用于9个子类别。
从matplotlib generic colormap from tab10中选取categorical_cmap
可获得每种色调更多的阴影。
import numpy as np
import matplotlib.pyplot as plt
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
y =np.array([17, 16, 10, 8 ,6, 5, 5, 4, 3, 17 ,2 ,1, 1, 3, 2 ])
x = np.array([74 ,21 ,5])
fig, ax = plt.subplots()
size = 0.3
cmap = categorical_cmap(3, 10)
outer_colors = cmap(np.array([0, 10, 20]))
ar = np.concatenate((np.arange(1,10), [13,15,17,19], [25,30]))
inner_colors = cmap(ar)
ax.pie(x, radius=1, colors=outer_colors,
wedgeprops=dict(width=size, edgecolor='w'))
ax.pie(y, radius=1-size, colors=inner_colors,
wedgeprops=dict(width=size, edgecolor='w'))
ax.set(aspect="equal", title='Pie plot with `ax.pie`')
plt.show()
或者,可以使用三种不同的连续颜色图,并采用其中一些颜色。
import numpy as np
import matplotlib.pyplot as plt
y =np.array([17, 16, 10, 8 ,6, 5, 5, 4, 3, 17 ,2 ,1, 1, 3, 2 ])
x = np.array([74 ,21 ,5])
fig, ax = plt.subplots()
size = 0.3
cmap1 = plt.cm.Reds
cmap2 = plt.cm.Purples
cmap3 = plt.cm.Greens
outer_colors = [cmap1(.8), cmap2(.8), cmap3(.8)]
inner_colors = [*cmap1(np.linspace(.6, .1, 9)),
*cmap2(np.linspace(.6, .2, 4)),
*cmap3(np.linspace(.6, .2, 2))]
ax.pie(x, radius=1, colors=outer_colors,
wedgeprops=dict(width=size, edgecolor='w'))
ax.pie(y, radius=1-size, colors=inner_colors,
wedgeprops=dict(width=size, edgecolor='w'))
ax.set(aspect="equal", title='Pie plot with `ax.pie`')
plt.show()