0

I would like to add a title to pie chart with legend at right. Currently, the title not at the 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)

    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")

How can I put the title at the center?

enter image description here

lucky1928
  • 8,708
  • 10
  • 43
  • 92
  • One quick thing - in the future, please don't include "`savefig`" statements or the like in your MWEs, unless that's the focus of your question. In general, include as little code as possible to get things working - see [How to create a Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example) – AJ Biffl Nov 20 '21 at 03:09

1 Answers1

1

It really depends what you mean by "center"

If you mean put it in the center of the pie chart, you can use matplotlib.axes.Axes.text

Example (replacing the ax.set_title line):

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

Output:

enter image description here

You can play around with the parameters to text to get things like different background colors or font size, etc. You can also use fig.transFigure instead of ax.transAxes to plot in figure coordinates as opposed to axes coordinates.

If you want the title to be centered on the top of the figure, use fig.suptitle instead of ax.set_title.

Output:

enter image description here

(Note that the y argument to suptitle is set to 0.85 in this one. See this question about positioning suptitle.)

AJ Biffl
  • 493
  • 3
  • 10