在子图中改善饼图的标签。

5

我正在绘制一个包含三个子图的图表:

fig = plt.figure(fignum)
ax11 = plt.subplot2grid((2,2), (0,0))
ax12 = plt.subplot2grid((2,2), (0,1))
ax13 = plt.subplot2grid((2,2), (1,0), colspan=2)
ax13.axis('off')

我正在使用Pandas处理数据,想要绘制柱状图、饼图和表格。我的操作如下:

d = pd.Series(data,index)

#plotting the first subplot
d.plot(kind='bar',ax=ax11)

#plotting the second one and adjusting size of labels and percentages
(wedges, texts, autotexts) = ax12.pie(d,labels=d.index,autopct='%1.1f%%')
ax12.axis('equal')
for t in texts:
        t.set_size(7)
for t in autotexts:
        t.set_size(7)

#plotting the third axes, the table
ax13.table(cellText=table,colLabels=columns,loc='bottom')

这是最终效果:

输入图像描述

如何使饼图看起来更好,而不会出现标签重叠的现象?我尝试添加一个图例,但它覆盖了图表,我甚至不知道它是否在我指定的位置上:

ax12.legend(index,loc='lower right',fontsize=7)

有没有办法将图例移到饼图下面的空白区域?一旦图例看起来不错,我会从饼图本身中删除标签。
1个回答

1
bbox_to_anchor 允许您在图形画布上定位图例。
请参见:http://matplotlib.org/users/legend_guide.html
import matplotlib.pyplot as plt
import pandas 

fig = plt.figure()
ax11 = plt.subplot2grid((2,2), (0,0))
ax11.bar([1,2,3,4,3,2,1],[1,2,3,4,3,2,1])
ax11.set_xticklabels(["local user","whetever works","L'ours tourne","en rond","dans sa cage",2,1], rotation="vertical")

ax12 = plt.subplot2grid((2,2), (0,1))
ax12.pie( [10,20,30,5,5,6,4,10,10], labels = ["bewarfefvl","easdfgvagfvd","asasdfve.sd","rgdegaf","adfewga","qargw","qaerghrttw","errrrd","ejjjjd"],autopct='%1.1f%%')
ax12.axis('equal')
ax12.legend(loc='lower right',fontsize=7, bbox_to_anchor = (0.75, -01.0) )


ax13 = plt.subplot2grid((2,2), (1,0), colspan=2)
ax13.axis('off')

plt.show()

尽管您可以跳过图例并通过调整饼图来提高其可读性,但我可以想到三种方法来做到这一点,但这绝不是详尽无遗的列表:
  1. 当将列表作为参数传递时,您可以通过交换列表中值的顺序来影响图表中每个切片的相对位置,以避免小切片的聚集。在pandas中可能有一种实现方法。
  2. labeldistance使您可以控制标签与图表之间的距离。
  3. 通过将第二个数组作为explode参数传递,您可以偏移每个切片的位置。
下面是一个简单的示例:
ax12 = plt.subplot2grid((2,2), (0,1))
labels = ["bewarfefvl","easdfgvagfvd","asasdfve.sd",
              "rgdegaf","adfewga","qargw","qaerghrttw","errrrd","ejjjjd"]
ax12.pie( [10,20,30,5,5,6,4,10,10], [0,0,0.0,0.1,0.3,.5,0,0,0], 
                          labels = labels, labeldistance=1.2)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接