0

I have a set of three variables for which I would like to calculate a boxplot. The three variables share the same title, and have different x label, and I want the three of them to be created in the same figure.

Look to the following example (with fake data):

import numpy as np
import matplotlib.pyplot as plt

data = dict(var1=np.random.normal(0, 1, 1000), var2=np.random.normal(0, 2, 1000), var3=np.random.normal(1, 2, 1000))
var_title = 'Really really long overlapping title'
fig = plt.figure()
for i in range(len(data)):
    plt.subplot(1, 3, i + 1)
    plt.boxplot(data[data.keys()[i]])
    plt.title(var_title)
    plt.show()

This code generates the following figure: enter image description here

Now, what I want is either to set just one title over the three subplots (since the title is the same) or get python to automatically redimension the figure so that the title fits and can be read.

I am asking for this because this figure creation is part of a batch process in which the figures are saved automatically and used on the generation of PDF documents, so I cannot be involved on changing the figure dimensions one at a time.

2 Answers2

2

In order to create a title for multiple subplots you can use Figure.suptitle instead of fig.title and format font size and such as specified there.

So your code will look like:

import numpy as np
import matplotlib.pyplot as plt

data = dict(var1=np.random.normal(0, 1, 1000), 
var2=np.random.normal(0, 2, 1000), var3=np.random.normal(1, 2, 1000))
var_title = 'Really really long overlapping title'
fig = plt.figure()
fig.suptitle(var_title)
for i in range(len(data)):
    plt.subplot(1, 3, i + 1)
    plt.boxplot(data[data.keys()[i]])
    plt.show()

Question is also answered here by orbeckst.

rLevv
  • 498
  • 3
  • 12
0

Based on the comment of @ImportanceOfBeingErnest you can do this:

import numpy as np
import matplotlib.pyplot as plt

data = dict(var1=np.random.normal(0, 1, 1000), var2=np.random.normal(0, 2, 1000), var3=np.random.normal(1, 2, 1000))
var_title = 'Really really long overlapping title' 


f, ax = plt.subplots(1, 3)
for i in range(len(data)):
    ax[i].boxplot(data[list(data.keys())[i]])
f.suptitle(var_title)
plt.show()

Result

Caio Belfort
  • 535
  • 2
  • 10