Alex Turner
Alex Turner

Reputation: 926

Xlabel fontsize don't change in plot

I'm trying to plot some data in different plots, and I'm able to do it, but, the labelsize from the x axis don't change in the first plot, but it does in the second one. This is what I'm doing:

import matplotlib.pyplot as plt
from dateutil.relativedelta import relativedelta as rd
from calendar import monthrange

fin_mes = date.today() - rd(days=1)
# Start ploting data A
fig, ax = plt.subplots(1, 1)
# Retrieve dates
mes = fin_mes.strftime("%B")
anio = fin_mes.strftime("%Y")
# Set title
plt.suptitle(f"Data {mes} - {anio}")
# List of days of the last month
num_days = range(1, int(monthrange(fin_mes.day, fin_mes.month)[1]) + 1)
print(num_days)
# Set name from x label
ax.set_xlabel('Dates')
# Set name from y label
ax.set_ylabel('Data')
# Set name from the plot to save
name_a = f"DataA-{mes}-{anio}.png"
plt.title("My Data")
plt.xlim(0, num_days[-1])
plt.ylim((min(num_days)),
         (max(num_days)))
plt.xticks(num_days)
# Setting the size to the label
plt.rc('xtick', labelsize=5)
plt.grid(True)
dataa_plot, = plt.plot(num_days, num_days, label="DATA A")
plt.legend(handles=[dataa_plot])
plt.show()
fig.savefig(name_a)


# Start ploting data B
fig, ax = plt.subplots(1, 1)
# Retrieve dates
mes = fin_mes.strftime("%B")
anio = fin_mes.strftime("%Y")
# Set title
plt.suptitle(f"Data {mes} - {anio}")
# List of days of the last month
num_days = range(1, int(monthrange(fin_mes.day, fin_mes.month)[1]) + 1)
print(num_days)
# Set name from x label
ax.set_xlabel('Dates')
# Set name from y label
ax.set_ylabel('Data')
# Set name from the plot to save
name_b = f"DataB-{mes}-{anio}.png"
plt.title("My Data B")
plt.xlim(0, num_days[-1])
plt.ylim((min(num_days)),
         (max(num_days)))
plt.xticks(num_days)
# Setting the size to the label
plt.rc('xtick', labelsize=5)
plt.grid(True)
datab_plot, = plt.plot(num_days, num_days, label="DATA B")
plt.legend(handles=[datab_plot])
plt.show()
fig.savefig(name_b)

With that I get this plots:

Plot from Data A

enter image description here

And plot b has the font size changed, but not plot A. I don't know why this is happening. Hope someone can help me, thanks.

PD: I'm using python 3.8.10 in Lubuntu x64 with matplotlib=3.5.1

Upvotes: 1

Views: 725

Answers (1)

Stef
Stef

Reputation: 30579

You must set the label size before using it in setting the ticks, i.e. plt.rc('xtick', labelsize=5) must come before plt.xticks(num_days) to take effect (the safest way is to move it to the very beginning of the plotting).

As an (easier) alternative you can set the font size directly in xticks without changing the rc parameters:

plt.xticks(num_days, fontsize=5)

Upvotes: 1

Related Questions