【发布时间】:2021-11-20 01:53:33
【问题描述】:
我想为饼图添加一个标题,右侧有图例。目前,标题不在中心!
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
def plot(df,xname,yname,pngname):
title = "sample title"
x = df[xname]
y = df[yname]
fig, ax = plt.subplots(figsize=(5, 5))
patches, texts = ax.pie(x,#autopct='%.1f%%',
startangle=90, radius=1.2,
wedgeprops={'linewidth': .1, 'edgecolor': 'white'},
textprops={'size': 'x-large'})
labels = ['{1:1.1f} {0}'.format(i,j) for i,j in zip(y,x)]
patches, labels, dummy=zip(*sorted(zip(patches, labels, x),
key=lambda x: x[2],
reverse=True))
plt.legend(patches, labels,
frameon=False,
loc='center left',
bbox_to_anchor=(1, 0.5),
labelspacing=0,
#handletextpad=0.1,
fontsize=12)
ax.set_title(title)
plt.tight_layout()
fig.savefig(pngname, dpi=fig.dpi, bbox_inches="tight")
print("[[./%s]]"%pngname)
return
df = pd.DataFrame({
'key': ['AAAA', 'BBBB', 'CCCC', 'DDDD'],
'value':[ 20 ,6, 6, 8]})
plot(df,"value","key","demo.png")
如何将标题放在中心?
【问题讨论】:
-
一件快速的事情 - 将来,请不要在您的 MWE 中包含“
savefig”声明或类似内容,除非这是您问题的重点。一般来说,包含尽可能少的代码以使事情正常运行 - 请参阅How to create a Minimal, Reproducible Example
标签: python matplotlib