lucky1928
lucky1928

Reputation: 8849

matpliblib - Add title to pie chart center with legend

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

Upvotes: 0

Views: 1962

Answers (1)

AJ Biffl
AJ Biffl

Reputation: 584

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

Upvotes: 1

Related Questions