pythonpandasmatplotlibyaxistwinx

How to adjust the ticks and label size of a pandas plot with secondary_y


I have a plot with a left and right y-axis created with pandas.DataFrame.plot and specifying secondary_y=True.

I want to increase the font sizes of the y-axis tick params, but it seems that only the left side y-axis font size is increasing.

import pandas as pd
import numpy as np

# sample dataframe
sample_length = range(1, 2+1)
rads = np.arange(0, 2*np.pi, 0.01)
data = np.array([np.sin(t*rads) for t in sample_length])
df = pd.DataFrame(data.T, index=pd.Series(rads.tolist(), name='radians'), columns=[f'freq: {i}x' for i in sample_length])

# display(df.head(3))
         freq: 1x  freq: 2x
radians                    
0.00     0.000000  0.000000
0.01     0.010000  0.019999
0.02     0.019999  0.039989

# plot
ax1 = df.plot(y='freq: 1x', ylabel='left-Y', figsize=(8, 5))
df.plot(y='freq: 2x', secondary_y=True, ax=ax1)

ax1.tick_params(axis='both', labelsize=20)

enter image description here

What is the way to increase the font size for the right y-axis?


Solution

  • # plot the primary axes
    ax1 = df.plot(y='freq: 1x', ylabel='left-Y', figsize=(8, 5))
    
    # add the secondary y axes and assign it
    ax2 = df.plot(y='freq: 2x', secondary_y=True, ax=ax1)
    
    # adjust the ticks for the primary axes
    ax1.tick_params(axis='both', labelsize=14)
    
    # adjust the ticks for the secondary y axes
    ax2.tick_params(axis='y', labelsize=25)
    
    # set the primary (left) y label
    ax1.set_ylabel('left Y', fontsize=18)
    
    # set the secondary (right) y label from ax1
    ax1.right_ax.set_ylabel('right-Y', fontsize=30)
    
    # alternatively (only use one): set the secondary (right) y label from ax2
    # ax2.set_ylabel('right-Y', fontsize=30)
    
    plt.show()
    

    enter image description here

    Note

    ax = df.plot(ylabel='left-Y', secondary_y=['freq: 2x'], figsize=(8, 5))
    
    ax.tick_params(axis='both', labelsize=14)
    ax.right_ax.tick_params(axis='y', labelsize=25)
    
    ax.set_ylabel('left Y', fontsize=18)
    
    # set the right y axes
    ax.right_ax.set_ylabel('right-Y', fontsize=30)