The following MWE:
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
# Use latex
import os
os.environ["PATH"] += os.pathsep + '/usr/local/texlive/2024/bin/x86_64-linux'
if __name__ == '__main__':
test_data = 10
test_data_2 = 24
# Create plot and axis
fig, ax = plt.subplots()
plt.rcParams.update({
"text.usetex": True,
"font.family": "serif",
"font.serif": "Computer Modern Roman",
})
# Plot
ax.plot([i for i in range(test_data)], [i for i in range(test_data)], label="Test")
ax.tick_params(bottom=False)
# Define x axis
x_axis = ['30', '40', '50'] * (test_data_2 // 3)
ax.set_xticks(range(len(x_axis)), labels=(x_axis))
# Add second x axis
sec2 = ax.secondary_xaxis(location=0)
sec2.set_xticks([5.5 + 12 * i for i in range(test_data_2 // 12)],
labels=[f'\n\n\n{5 + i * 5}' for i in range(test_data_2 // 12)])
sec2.tick_params('x', length=0)
plt.show()
Produces the following plot:
As one can see the secondary x axis with only 5 and 10 is in another font than the first axis.
I tried setting the labels separately by using ax.set_xticklabels or the same for sec2.set_... but this produced the same results. Also, formatting the text further like adding $$ or $\frac{..}$ yielded the same differences in font.
I would like to have uniform font and would prefer if the secondary x axis used the same font as the primary x axis.
How can I achieve this?
You are setting the font family and turning on uselatex
after you have created the Figure and primary Axes objects, but before you create the secondary Axes.
If you want everything to be using LaTeX and the serif font, then just set the relevant rcParams
before you create the figure.
i.e. move fig, ax = plt.subplots()
to after plt.rcParams.update(...)
.
You do say that you would like everything to use the font currently in use on the primary Axes though. If this is the case, you can just remove the rcParams
that you have here, and everything will have the font of the primary Axes. But then you won't be using LaTeX, so that might not be what you actually want.