Legend for a pie chart(饼图的图例)
本文介绍了饼图的图例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想创建一个带有标签和值的图例。 数据集包含此列
ID LETTER
2 C
26 C
40 C
63 D
83 E
139 C
141 E
145 C
148 E
156 E
我正在使用饼图:
from itertools import chain
from collections import Counter
import matplotlib.pyplot as plt
plt.figure(figsize=(16,8))
cts = Counter(chain.from_iterable(df.LETTER.str.split('|').values))
_ = plt.pie(cts.values(), labels=cts.keys(), autopct='%1.1f%%')
patches = cts.values()
labels = cts.keys()
sort_legend = True
if sort_legend:
patches,labels, dummy = zip(*sorted(zip(patches, labels, df.LETTER),
key=lambda x: x[2],
reverse=True))
plt.legend(cts.values(), labels=cts.keys(), loc='center left', bbox_to_anchor=(-0.1, 1.),
fontsize=8)
运行上面的代码,我得到一个图例表,它不包含任何值,只包含标签。我不希望在饼图中有任何标签或值,但只能在图例中。 您能告诉我如何修复代码吗?
谢谢
推荐答案
这是您预期的输出吗?我习惯了使用 pandas ,所以我正在使用数据帧。我已经指定了在引用的代码中获取的路径和标签。
import pandas as pd
import numpy as np
import io
data = '''
ID LETTER
2 C
26 C
40 C
63 O
83 N
139 C
141 O
145 C
148 N
156 N
'''
df = pd.read_csv(io.StringIO(data), delim_whitespace=True)
from itertools import chain
from collections import Counter
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(4,3),dpi=144)
ax = fig.add_subplot(111)
cts = df.LETTER.value_counts().to_frame()
percent = 100.*cts.LETTER / cts.LETTER.sum()
ax.pie(cts.LETTER)
patches = cts.index
labels = ['{0} - {1:1.2f} %'.format(i,j) for i,j in zip(cts.index, percent)]
sort_legend = True
if sort_legend:
patches,labels, dummy = zip(*sorted(zip(patches, labels, df.LETTER),
key=lambda x: x[2],
reverse=True))
plt.legend(patches, labels=labels, loc='center left', bbox_to_anchor=(-0.1, 1.), fontsize=8)
plt.show()
这篇关于饼图的图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:饼图的图例


基础教程推荐
猜你喜欢
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 求两个直方图的卷积 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 包装空间模型 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01