在matplotlib中移动绘图和图例

时间:2015-12-07 20:20:15

标签: python-2.7 matplotlib

我想在matplotlib中制作一个如下所示的饼图:

there

(颜色和边框的差异不是什么大问题。)

我不确定如何使用matplotlib实现这一点。

代码:

import matplotlib.pyplot as plt

g_title = "Big fat redacted title (Income Distribution)"
g_data_list = [['FIN.RES 47% - $41,888.08', 47], ['VSC 40% - $36,019.00', 40], ['AFTERMARKET 6% - $5,570.00', 6], ['GAP 7% - $6,528.00', 7]]

labels = []
sizes = []
for entry in g_data_list:
    labels.append(entry[0])
    sizes.append(entry[1])

patches, texts = plt.pie(sizes, startangle=90)
plt.legend(patches, labels, loc="center right", fontsize=6)
plt.axis('equal')
plt.title("{}".format(g_title), fontsize=14)
plt.savefig('test.png', dpi=100)

这给了

enter image description here

1 个答案:

答案 0 :(得分:2)

我不确定你喜欢什么,但一种选择是使用loc="best"

import matplotlib.pyplot as plt

g_title = "Big fat redacted title (Income Distribution)"
g_data_list = [['FIN.RES 47% - $41,888.08', 47],
               ['VSC 40% - $36,019.00', 40],
               ['AFTERMARKET 6% - $5,570.00', 6],
               ['GAP 7% - $6,528.00', 7]]

labels = []
sizes = []
for entry in g_data_list:
    labels.append(entry[0])
    sizes.append(entry[1])

patches, texts = plt.pie(sizes, startangle=90)
plt.legend(patches, labels, loc="best", fontsize=6)
plt.axis('equal')
plt.title(g_title, fontsize=14)
plt.savefig('test.png', dpi=300)

这给了

enter image description here

另一种选择是指定地块的大小并将图例固定到某个位置

import matplotlib.pyplot as plt

g_title = "Big fat redacted title (Income Distribution)"
g_data_list = [['FIN.RES 47% - $41,888.08', 47],
               ['VSC 40% - $36,019.00', 40],
               ['AFTERMARKET 6% - $5,570.00', 6],
               ['GAP 7% - $6,528.00', 7]]

labels = []
sizes = []
for entry in g_data_list:
    labels.append(entry[0])
    sizes.append(entry[1])

ax = plt.subplot(111)
box = ax.get_position()
ax.set_position([box.x0, box.y0, box.width * 0.7, box.height])
patches, texts = ax.pie(sizes, startangle=90)
ax.legend(patches, labels, loc='center left',
          bbox_to_anchor=(1, 0.5), fontsize=8)
plt.axis('equal')
plt.suptitle(g_title, fontsize=14)
plt.savefig('test.png', dpi=300)

导致

enter image description here