mavcp10
mavcp10

Reputation: 51

Matplotlib title and axis label padding

I'm just starting out experimenting with Matplotlib today. I've spent the last few hours trying to fix the positioning of the title and axis labels to no avail. I figured out to fix the spacing between the title and top of the chart and the axis labels and ticks using the padding parameter. I can't figure out how to make it so that the title is not crammed to top of the figure and the x/y axis labels aren't crammed to the left/bottom of the figure.

Below is an example that has nothing to do with my actual problem other than illustrating the formatting issue.

import matplotlib.pyplot as plt
import numpy as np

#create data
A = 5
f = 0.5
t = np.arange(0,10,0.01)
y = A * np.sin(2*np.pi*f*t)

#create plot
fig, ax = plt.subplots()
fig.set_size_inches(8*(16/9),8)
ax.plot(t,y)

#format plot
ax.spines.top.set_visible(False)
ax.spines.right.set_visible(False)
ax.set_title('Need this title to move down without moving into subplot so that it is not crammed on top',pad=20)
ax.set_ylabel('Need this label to move to the right',labelpad=20)
ax.set_xlabel('Need this label to move up',labelpad=20)

Example of formatting issue

Any suggestions as to how to increase the margins between the outside of the title/labels and the edge of the figure would be greatly appreciated.

Upvotes: 3

Views: 5820

Answers (1)

blunova
blunova

Reputation: 2532

You can try something like that:

import matplotlib.pyplot as plt
import numpy as np

#create data
A = 5
f = 0.5
t = np.arange(0, 10, 0.01)
y = A * np.sin(2 * np.pi * f * t)

#create plot
fig, ax = plt.subplots()
fig.set_size_inches(8 * (16 / 9), 8)
ax.plot(t, y)

#format plot
ax.spines.top.set_visible(False)
ax.spines.right.set_visible(False)

ax.set_title("Title", y=-0.1)

ax.set_xlabel("x-label")
ax.xaxis.set_label_position("top") 

ax.set_ylabel("y-label")
ax.yaxis.set_label_position("right") 

enter image description here

If you want to move x/y-ticks on top/to the right as well, then use the following commands:

ax.xaxis.tick_top()
ax.yaxis.tick_right()

and then modify:

ax.spines.top.set_visible(False)
ax.spines.right.set_visible(False)

to

ax.spines.bottom.set_visible(False)
ax.spines.left.set_visible(False)

enter image description here

Upvotes: 1

Related Questions