Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add an extra y-axis label in matplotlib

I'm trying to add an additional axis label on the right side of an axis, but don't want ticks nor tick labels.

import pandas as pd
import matplotlib.pyplot as plt

fig, axs = plt.subplots(2,2,sharey=True,sharex=True)
for i in range(2):
    for j in range(2):
        pd.Series(np.random.random(10)).plot(ax=axs[i,j])
        axs[0,j].set_title('j = {}'.format(j))
    ax[1,j].set_ylabel('x')
    secaxy = axs[i,1].secondary_yaxis('right')
    secaxy.set_ylabel('i = {}'.format(i))
    secaxy.set_yticks([])
    ax[i,0].set_ylabel('y')

For some reason the set_yticks([]) doesn't replace the ticks.

[In]: secaxy.get_yticks()
[Out:] array([-0.25,  0.  ,  0.25,  0.5 ,  0.75,  1.  ,  1.25])

What would be a convenient way to get an additional axis label on the right side of the plot without ticks?

correct labels, but need to remove the ticks on the right

like image 419
Artturi Björk Avatar asked Jan 29 '26 22:01

Artturi Björk


1 Answers

I wouldn't misuse a secondary axes for that. Just put the label to the right and turn it visible.

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

fig, axs = plt.subplots(2,2,sharey=True,sharex=True) 
for i in range(2):
    for j in range(2):
        pd.Series(np.random.random(10)).plot(ax=axs[i,j])
for j in range(2):
    axs[0,j].set_title('j = {}'.format(j))
for i in range(2):
    axs[i,1].set_ylabel('i = {}'.format(i))
    axs[i,1].yaxis.get_label().set_visible(True)
    axs[i,1].yaxis.set_label_position("right")
    axs[i,0].set_ylabel('y')

plt.show()

enter image description here

like image 173
ImportanceOfBeingErnest Avatar answered Feb 01 '26 10:02

ImportanceOfBeingErnest



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!