Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib subplot title, figure title formatting

How would I go about formatting the below pie chart subplots so that there is more white-space between the fig title and subplot titles. Ideally the subplot titles would also be in closer vicinity to the actual pie chart itself.

I can't seem to find anything in the docs which might enable this, but I'm new to matplotlib.

matplotlib figure

import matplotlib.pyplot as plt
import pandas as pd
from pandas import DataFrame, Series

m = {"Men" :  {"Yes": 2, "No": 8}}
w = {"Women": {"Yes": 3, "No": 7}}
data = {**m, **w}
df = DataFrame(data)

fig, axes = plt.subplots(1, len(df.columns))
fig.suptitle("Would you prefer to work from home?", fontsize=18)
logging.debug("fig.axes: {}".format(fig.axes))

for i, ax in enumerate(fig.axes):
    col = df.ix[:, i]
    ax = fig.axes[i]
    pcnt_col = col / col.sum() * 100
    ax.set_title("{} (n={})".format(pcnt_col.name, col.sum()))
    ax.pie(pcnt_col.values, labels=pcnt_col.index,
                    autopct="%1.1f%%", startangle=90)
    ax.axis("equal")
    plt.legend(loc="lower right", title="Answer", fancybox=True,
               ncol=1, shadow=True)
plt.show()
like image 999
Michael Johnson Avatar asked Jul 02 '26 03:07

Michael Johnson


1 Answers

Use subplots_adjust to separate the two

plt.subplots_adjust(top=0.75)

import matplotlib.pyplot as plt
import pandas as pd
from pandas import DataFrame, Series

m = {"Men" :  {"Yes": 2, "No": 8}}
w = {"Women": {"Yes": 3, "No": 7}}
data = {**m, **w}
df = DataFrame(data)

fig, axes = plt.subplots(1, len(df.columns))
fig.suptitle("Would you prefer to work from home?", fontsize=18)
logging.debug("fig.axes: {}".format(fig.axes))

for i, ax in enumerate(fig.axes):
    col = df.ix[:, i]
    ax = fig.axes[i]
    pcnt_col = col / col.sum() * 100
    ax.set_title("{} (n={})".format(pcnt_col.name, col.sum()))
    ax.pie(pcnt_col.values, labels=pcnt_col.index,
                    autopct="%1.1f%%", startangle=90)
    ax.axis("equal")
    plt.legend(loc="lower right", title="Answer", fancybox=True,
               ncol=1, shadow=True)
plt.subplots_adjust(top=0.55)
plt.show()

enter image description here

like image 77
piRSquared Avatar answered Jul 03 '26 16:07

piRSquared



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!