如何左对齐Python Matplotlib饼图?

时间:2017-02-20 14:26:51

标签: python matplotlib pie-chart

我有一个左对齐标题的饼图:

import matplotlib.pyplot as plt

# Pie chart, where the slices will be ordered and plotted counter-clockwise:
sizes = [15, 30, 45, 10]

fig1, ax1 = plt.subplots()
ax1.pie(sizes, autopct='%1.1f%%', startangle=90)
ax1.axis('equal')
ax1.set_title('Pie Title', loc='left')

plt.tight_layout()
plt.savefig(r'C:\images\pie.png', bbox_inches='tight')

此代码生成此图像:

Pie Chart

但是饼图周围有太多的空白。如何左对齐标题和饼图并裁剪不必要的空格?

Left Align Pie Chart

2 个答案:

答案 0 :(得分:1)

你可以从方形图开始,例如: figsize=(4,4)
然后,您可以添加一些空格以使标题对齐。

import matplotlib.pyplot as plt

sizes = [15, 30, 45, 10]

fig1, ax1 = plt.subplots(figsize=(4,4))
ax1.pie(sizes, autopct='%1.1f%%', startangle=90)
ax1.axis('equal')
ax1.set_title('  Pie Title', loc='left')

plt.tight_layout()
plt.savefig(__file__+"pie.png", bbox_inches='tight')
plt.show()

enter image description here

如果此空白空间不够,您可以使用subplots_adjust进行游戏,例如plt.subplots_adjust(bottom=0, top=0.93, left=0.0, right=1)

答案 1 :(得分:0)

我认为你不能以中心,左或右的方式移动set_title。你可以做的是添加这样的文字:

ax1.text(-0.8, 1, 'Pie Title')

请参阅此处有关如何更改字体等的文档:http://matplotlib.org/users/text_props.html