从饼图中删除标签会移动图例框

时间:2017-04-14 17:50:40

标签: python pandas matplotlib

我试图在饼图中删除标签。目前我正在这样做:

qx = queens_tree_types.plot(ax=axes[0], kind='pie', figsize=(8,30), legend=True, 
                            autopct='%1.0f%%', pctdistance=0.9, radius=1.2)
axes[0].set_title('Queens');

这给了我以下的馅饼:

enter image description here

这很好,但我想从图表中删除标签。当我尝试简单地做labels=None时,我得到了这张照片:

enter image description here

初始饼图的设置位置如下所示:

qx.legend(bbox_to_anchor=(2.5, 1.05),
      ncol=2, fancybox=True, shadow=True)

但是当我删除标签时,我似乎无法移动图例框。是什么给了什么?

1 个答案:

答案 0 :(得分:5)

考虑将图例放在饼图旁边,因为默认图例放置覆盖在同一图上的饼图上。下面用虚构数据演示:

数据

import pandas as pd
import numpy as np

df = pd.melt(pd.DataFrame(np.random.randint(0,10,size=(20, 10)), 
                          columns=['Hulkeberry Finn', 'Captain Ahab', 'Hester Prynne', 
                                   'Nick Carraway', 'Bigger Thomas', 'Scout Finch', 
                                   'Invisible Man', 'Denver',
                                   'Tom Joad', 'Edna Pontellier']),
             var_name='group')
df = df.groupby(['group']).sum()

饼图1 (默认图例叠加)

from matplotlib import rc, pyplot as plt

# GENERAL STYLE SETTINGS
font = {'family' : 'arial', 'weight': 'bold', 'size': 10}
rc('font', **font); rc("figure", facecolor="white"); rc('axes', edgecolor='darkgray')

# GRAPH WITH LEGEND
qx = df.plot(kind='pie', figsize=(8,8), y='value', labels=None,
             autopct='%1.0f%%', pctdistance=0.9, radius=1.2)
plt.legend(loc="center right", fontsize=10)

plt.title('Pie Chart Demonstration', weight='bold', size=14)

plt.show()
plt.clf()
plt.close()

Pie Chart Overlay Legend Output

饼图2 (附近的子图)

plt.gca().axis("equal")
pie = plt.pie(df, startangle=0, autopct='%1.0f%%', pctdistance=0.9, radius=1.2)
labels=df.index.unique()
plt.title('Pie Chart Demonstration', weight='bold', size=14)
plt.legend(pie[0],labels, bbox_to_anchor=(1,0.5), loc="center right", fontsize=10, 
           bbox_transform=plt.gcf().transFigure)
plt.subplots_adjust(left=0.0, bottom=0.1, right=0.85)

plt.show()
plt.clf()
plt.close()

Pie Chart Subplot Legend Output