目录
一.引言
二.颜色选择
三.绘制饼图
四.总结
一.引言
因工作需求,需要绘制一些数据的饼图,使用默认的颜色绘制不够美观,下面我们找一些好看的颜色美化一些饼图。
二.颜色选择
我们根据 plt 给出的一些好看颜色对应的编码即可为每一个 pie 配置好看的颜色,通过 colors 为每一个 pie 指定颜色,博主这里简单挑选了一些比较清新的颜色,大家也可以自己把文字识别出来选择自己喜欢的颜色构建列表。
colors = ["snow", "lightsalmon", "orange", "lightyellow", "greenyellow", "palegreen", "springgreen","lightgreen", "aquamarine", "lightblue", "mediumpurple", "lightpink", "lightskyblue", "grey","mistyrose", "linen", "honeydew", "lightcyan", "lavender", "thistle", "black", "tan", "darkblue","indigo"]
三.绘制饼图
import matplotlib.pyplot as pltimport random# 待绘制的数据 Label -> Countdata = {'A': 8, 'B': 4, 'C': 5, 'D': 4, 'E': 3, 'F': 3}labels = data.keys()counts = data.values()# 随机颜色列表colors = ["snow", "lightsalmon", "orange", "lightyellow", "greenyellow", "palegreen", "springgreen","lightgreen", "aquamarine", "lightblue", "mediumpurple", "lightpink", "lightskyblue", "grey","mistyrose", "linen", "honeydew", "lightcyan", "lavender", "thistle", "black", "tan", "darkblue","indigo"]random.shuffle(colors)# 绘制饼图,百分比后再保留1位plt.title(f"Total - {sum(counts)}")plt.pie(counts, labels=labels, colors=colors[:len(labels)], autopct='%1.1f%%', startangle=140)plt.legend(labels, title="Keys", loc='upper left', bbox_to_anchor=(1, 1))plt.show()
这里我们把挑选了一些好看的颜色,并且每次采用随机的策略,这样每次运行得到的饼图颜色都是随机的,下面随机两把看看效果怎么样:
四.总结
由于选择的颜色比较淡,有时候也会出现看不清的情况,大家根据自己的需求构建 colors 列表即可。还有一些 legend 的参数这里不多赘述了,有需要的同学可以自行搜索调整。