Matplotlib带右侧图例的饼图如何将标题设置在饼图中心位置
Matplotlib饼图标题居中解决方案
问题原因
ax.set_title() 默认以整个坐标轴(Axes)区域的顶部中心作为对齐基准,你当前的配置中将图例放在坐标轴右侧,同时设置了饼图radius=1.2,坐标轴的水平范围预留了图例的展示空间,因此默认标题会和整个坐标轴对齐,无法对准左侧的饼图区域。
两种适配方案
方案1:调整标题位置,放在饼图正上方
修改ax.set_title的参数,手动指定x轴对齐位置,适配饼图的水平中心:
# 替换原有的ax.set_title(title)行 ax.set_title(title, x=0.42, fontsize=14)
参数说明:
x参数取值范围0-1,代表在坐标轴水平方向的相对位置,你可以根据最终展示效果微调数值,0.42适配当前代码的配置- 也可以额外加
y参数调整垂直高度
方案2:直接将标题放在饼图内部中心
如果需要标题显示在饼图的圆心位置,直接使用ax.text绘制,对齐精度更高,不受坐标轴范围影响:
# 替换原有的ax.set_title(title)行 ax.text(0, 0, title, ha='center', va='center', fontsize=15)
参数说明:
- 饼图默认坐标系以(0,0)为圆心,直接填该坐标即可精准对准饼图中心
ha='center'设置水平居中,va='center'设置垂直居中
调整后完整代码示例
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) # 这里替换为你选的方案即可,示例用方案2放饼图中心 ax.text(0, 0, title, ha='center', va='center', fontsize=15) 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")
内容的提问来源于stack exchange,提问作者lucky1928
相关产品推荐
相关产品推荐

