【问题标题】:matpliblib - Add title to pie chart center with legendmatplotlib - 将标题添加到带有图例的饼图中心
【发布时间】: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


【解决方案1】:

这真的取决于你所说的“中心”是什么意思

如果你的意思是把它放在饼图的中心,你可以使用matplotlib.axes.Axes.text

示例(替换 ax.set_title 行):

ax.text(0.5, 0.5, 'sample title', transform = ax.transAxes, va = 'center', ha = 'center', backgroundcolor = 'white')

输出:

您可以使用text 的参数来获取不同的背景颜色或字体大小等内容。您还可以使用fig.transFigure 而不是ax.transAxes 来绘制图形坐标而不是轴坐标。

如果您希望标题在图的顶部居中,请使用fig.suptitle 而不是ax.set_title

输出:

(请注意,suptitley 参数在此设置为 0.85。有关定位 suptitle 的信息,请参阅 this question。)

【讨论】:

  • 我希望 (0.5,0.5) 是图形的中心,但实际上它不包括图例部分。所以它仍然是馅饼的中心。
  • @lucky1928 查看对帖子所做的编辑
猜你喜欢
  • 1970-01-01
  • 2016-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-05
  • 2019-05-28
相关资源
最近更新 更多