Reputation: 1220
I am looking for the most concise way to set axis labels and their font size.
I am aware I can do this:
ax.set_xlabel('X axis', fontsize = 12)
ax.set_ylabel('Y axis', fontsize = 12)
I also know I can use this command to set the labels instead:
ax.set(xlabel = 'X axis', ylabel = 'Yaxis')
However, if I try:
ax.set(xlabel = 'X axis', ylabel = 'Yaxis', fontsize = 12)
I get this error:
TypeError: There is no AxesSubplot property "fontsize"
Can I denote the fontsize within the set
method? I'd like to tidy up my code a bit and be as concise as possible.
Upvotes: 16
Views: 48643
Reputation: 23449
ax.xaxis.label
or ax.yaxis.label
also return a matplotlib.text.Text
object, so you can call set()
or set_size()
on it to change the fontsize (you can also change the position with the former).
ax.xaxis.label.set_size(20)
A working example:
fig, ax = plt.subplots(figsize=(5,3))
ax.plot(range(10), range(10))
ax.set(xlabel='Time', ylabel='Value')
ax.xaxis.label.set(fontsize=20, position=(0.9, 0))
ax.yaxis.label.set(fontsize=15, position=(0, 0.9))
Upvotes: 0
Reputation: 942
You could change the label for each "axis" instance of the "axes". The text instance returned by "get_label" provides methods to modify the fonts size, but also other properties of the label:
from matplotlib import pylab as plt
import numpy
fig = plt.figure()
ax = fig.add_subplot(111)
ax.grid()
# set labels and font size
ax.set_xlabel('X axis', fontsize = 12)
ax.set_ylabel('Y axis', fontsize = 12)
ax.plot(numpy.random.random(100))
# change font size for x axis
ax.xaxis.get_label().set_fontsize(20)
plt.show()
Upvotes: 15