为不同饼图中的每个标签保留相同的颜色

问题描述 投票:0回答:1

我在从一个饼图到另一个饼图的每个标签上都难以保持相同的颜色。如下图所示,Matplotlib只是自动将蓝色分配给比例最高的标签。我想例如将蓝色标记为“否”,将橙色标记为“是”。enter image description here

这是我的代码:

fig, ax = plt.subplots(1, 3, figsize=(18,5))

data_mhr_low = data.loc[data.max_heart_rate_cat == 'Low']
data_mhr_medium = data.loc[data.max_heart_rate_cat == 'Medium']
data_mhr_high = data.loc[data.max_heart_rate_cat == 'High']

data_mhr_low['has_heart_disease'].value_counts().plot.pie(explode=[0,0.1],autopct='%1.1f%%',ax=ax[0],shadow=True)
data_mhr_medium['has_heart_disease'].value_counts().plot.pie(explode=[0,0.1],autopct='%1.1f%%',ax=ax[1],shadow=True)
data_mhr_high['has_heart_disease'].value_counts().plot.pie(explode=[0,0.1],autopct='%1.1f%%',ax=ax[2],shadow=True)
python matplotlib pie-chart
1个回答
0
投票

matplotlib.pyplot.pie具有参数colors,饼图将通过该参数循环。这是两个如何使用它的示例。

import matplotlib.pyplot as plt
import numpy as np

# Pie chart, where the slices will be ordered and plotted counter-clockwise:
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
sizes = [15, 30, 45, 10]
explode = (0, 0.1, 0, 0)  # only "explode" the 2nd slice (i.e. 'Hogs')

fig = plt.figure()

ax1 = fig.add_subplot(121)
ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%')

cmap = plt.cm.prism
colors = cmap(np.linspace(0., 1., len(labels)))
ax2 = fig.add_subplot(122)
ax2.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%', colors=colors)

plt.show()

enter image description here

import matplotlib.pyplot as plt

# Pie chart, where the slices will be ordered and plotted counter-clockwise:
labels = 'Frogs', 'Hogs'
sizes = [15, 30]
explode = (0, 0.1)  # only "explode" the 2nd slice (i.e. 'Hogs')

fig = plt.figure()

colors1 = ["orange", "red"]
ax1 = fig.add_subplot(121)
ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%', colors=colors1)

colors2 = ["orange", "blue"]
ax2 = fig.add_subplot(122)
ax2.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%', colors=colors2)

plt.show()

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.