【发布时间】:2020-04-13 15:21:58
【问题描述】:
我想从两组数据中构建两个饼图,这些数据在标签中有一些重叠,例如标签是这样的:
labels_a = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "Other"]
labels_b = ["one", "two", "four", "three", "six", "eleven", "twelve", "five", "eight", "nine", "Other"]
所以six出现在两者中,但在不同的位置,也有一些标签只出现在一组中。两者都包含Other(但在我的真实情况下可能没有)。
我现在想用这些标签和相应的数据绘制两个饼图,其中每个图表中的相同标签具有相同的颜色,即我希望与 six 对应的楔形出现在两个饼图中,并带有相同的颜色。此外,我希望有一个图例,其中包含两个饼图的所有条目。
这是我的代码:
import pandas as pd
import os
import matplotlib.pyplot as plt
# define two color sets that differ
colors = plt.get_cmap("Set1").colors + plt.get_cmap("Dark2").colors
alt_colors = plt.get_cmap("Set3").colors + plt.get_cmap("Set2").colors
labels_a = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "Other"]
labels_b = ["one", "two", "four", "three", "six", "eleven", "twelve", "five", "eight", "nine", "Other"]
values_a = [500, 300, 250.0, 221.0, 164.0, 135.0, 111, 110, 100.0, 91.8, 2200]
values_b = [440, 320, 250.0, 220.0, 164.0, 135.0, 120, 100, 90.0, 70, 2200]
fig, axs = plt.subplots(2,1)
cols_a = list(colors[:len(labels_a)]) # choose the first 11 colors for the a-labels
if "Other" in labels_a: # make sure that Other gets the right color
cols_a[labels_a.index("Other")] = colors[-1]
# set a color map for the b-labels:
cols_b = []
for i in labels_b:
if i in labels_a:
cols_b.append(cols_a[labels_a.index(i)])
else:
cols_b.append(alt_colors[labels_b.index(i)])
if "Other" in labels_b: # make sure that Other gets the same color
cols_b[labels_b.index("Other")] = colors[-1]
wedges_a, text_a = axs[0].pie(values_a, labels=labels_a, colors=cols_a, startangle=-90)
wedges_b, text_b = axs[1].pie(values_b, colors=cols_b, labels= labels_b, startangle=-90)
plt.legend(wedges_a, labels_a, loc="lower right")
它工作得很好,因为它为每个标签分配了正确的颜色。如何实现包含所有条目的图例?我怎样才能把它放在饼图之外,即避免这种重叠:
【问题讨论】:
标签: matplotlib