【问题标题】:Legend for a pie chart饼图的图例
【发布时间】:2021-02-16 01:34:23
【问题描述】:

我想创建一个带有标签和值的图例。 数据集包含此列

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)

运行上面的代码,我得到一个图例表,它不包含任何值,但只有标签。我希望饼图中没有任何标签或值,而仅在图例中。 你能告诉我如何修复代码吗?

谢谢

【问题讨论】:

  • 为什么我们不停止显示标签和值的百分比? _ = plt.pie(cts.values())
  • @r.beginniers,我已经尝试过了,但问题是在图例中我看不到值。即使我标注也没关系
  • 可以分享当前的输出图吗?还有,这是做什么的?df.LETTER.str.split('|').values
  • 您只能使用 df.Letter.values。我把清理过的文本。那行代码需要将一个字符串分成两部分。
  • 我试图按照以下步骤操作:stackoverflow.com/questions/23577505/…,但我更喜欢标注而不是图例(如果可能且容易的话)

标签: python pandas matplotlib pie-chart


【解决方案1】:

这是您期望的输出吗?我习惯使用熊猫,所以我使用的是数据框。我已经指定了引用代码中获得的路径和标签。

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()

【讨论】:

  • 使用问题中的数据,在绘制图表时复制并使用代码。
猜你喜欢
  • 2011-05-28
  • 2019-06-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-31
  • 1970-01-01
  • 2014-10-08
  • 2016-09-24
相关资源
最近更新 更多