【问题标题】:Legend on pie chart matplotlib饼图matplotlib上的图例
【发布时间】:2016-05-03 11:56:05
【问题描述】:

我正在尝试使我的图例的框更小,并放置在我的饼图的左上角。到目前为止,我有: pumsData = pd.DataFrame.from_csv('ss13hil.csv')

pieLabels = ['English Only','Spanish','Other Indo-European','Asian and Pacific Island Languages','Other']  
plt.pie(pumsData.HHL.value_counts())  
plt.axis('equal')  
plt.title('Household Languages')  
plt.legend(pieLabels,loc=2,borderpad=0.05)  

我的图表的输出是:
http://i.stack.imgur.com/WbO4U.png

但我希望它看起来像这样:

http://i.stack.imgur.com/cBxLz.png

enter code here

【问题讨论】:

  • 你是问如何让字体变小?

标签: matplotlib charts


【解决方案1】:

如果您明确地将坐标区实例创建为对象,而不仅仅是使用 pyplot 模块中的函数,则可以更轻松地访问绘图属性。使用bbox_to_anchor=(0.5,0.90) 作为ax.legend() 中的参数,您可以移动图中的图例。试试这个代码:

import matplotlib.pyplot as plt

pieLabels = ['English Only',
             'Spanish',
             'Other Indo-European',
             'Asian and Pacific Island Languages',
             'Other']  

fig, ax  = plt.subplots(1,1,figsize=(4,4))

ax.pie([1,2,3,4,5], labels=pieLabels, labeldistance=9999999)
ax.set(adjustable='box-forced', aspect='equal')
ax.set_title('Household Languages')

handles, labels = ax.axes.get_legend_handles_labels()
ax.legend(handles, labels, prop={'size':6},
          bbox_to_anchor=(0.5,0.90),
          bbox_transform=fig.transFigure)

plt.show()

它应该产生这个数字:

【讨论】:

  • 看到其他人推荐 OO api 让我很高兴 :)
  • @tcaswell 它让一切变得如此简单
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-05
  • 1970-01-01
  • 2011-08-09
  • 1970-01-01
  • 2011-05-28
相关资源
最近更新 更多