Home > OS >  Change Font Size on secondary Y axis
Change Font Size on secondary Y axis

Time:07-15

I am writing code for my internship and I am trying to modify the font size on my axes so that it can look a bit better. The section that does not seem to be working is this part.

    ax.set_xticks([-95, -97, -99, -101, -103])
    
    ax.set_yticks([33, 34, 35, 36, 37])

    secax = ax.secondary_yaxis(1.0)
    secax.set_yticks([33, 34, 35, 36, 37])        

    ax.tick_params(axis = 'both', labelsize = 16)

When I run all of my code x axis and first y axis font size changes fine but my secondary y axis font size does not change. Is there any way I can change the font size of my secondary y axis?This is the output I get when I run the code

CodePudding user response:

In your code, ax.tick_params(axis = 'both', labelsize = 16) changes font size for primary axes. To set fonts for secondary axis add the line secax.tick_params(labelsize=16).

Here's a working MRE

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()

xdata = list(range(10))
yF = 85   10*np.random.random((10,1))

def fahrenheit_to_celsius(x):
    return (x - 32) / 1.8

def celsius_to_fahrenheit(x):
    return x * 1.8   32


yC = (yF-32)/1.8

ax.plot(xdata, yF)
secax = ax.secondary_yaxis('right', functions = (fahrenheit_to_celsius, celsius_to_fahrenheit))
ax.tick_params(axis = 'both', labelsize = 16)
secax.tick_params(labelsize = 16)

plt.show()

Another strategy is to add a block of code near the top of your file to control font sizes. I don't remember where I found this code, but it comes in handy. Interestingly setting xtick or ytick labelsize also works for secondary axes:

SMALL_SIZE = 10
MEDIUM_SIZE = 16
BIGGER_SIZE = 18

plt.rc('font', size=SMALL_SIZE)          # controls default text sizes
plt.rc('axes', titlesize=MEDIUM_SIZE)     # fontsize of the axes title
plt.rc('axes', labelsize=MEDIUM_SIZE)    # fontsize of the x and y labels
plt.rc('xtick', labelsize=MEDIUM_SIZE)    # fontsize of the tick labels
plt.rc('ytick', labelsize=MEDIUM_SIZE)    # fontsize of the tick labels
plt.rc('legend', fontsize=SMALL_SIZE)    # legend fontsize
plt.rc('figure', titlesize=BIGGER_SIZE)  # fontsize of the figure title

plt.rc('axes', titleweight='bold')     # fontsize of the axes title
plt.rc('axes', labelweight='bold')    # fontsize of the x and y labels
  • Related