'Share Y axis in Matplotlib with different ticks and labels

I want to plot 2 adjacent figures sharing the y axis but I want to specify different ticks and labels to the left of the left figure and to the right of the right figure. I am representing a logarithmic scale from high (bottom) to low values (top), but I don't think this is relevant.

My reproducible try:

values_1 = range(50)
log_values_1 = -np.log(values_1)

values_2 = range(100)
log_values_2 = -np.log(values_2)

fig, axs = plt.subplots(1, 2, figsize=(10,20), sharey=True)

for i in range(50):
    axs[0].axhline(log_values_1[i], color="blue")
axs[0].set_xticks([])
axs[0].set_yticks(log_values_1[::-1])
axs[0].set_yticklabels(values_1[::-1])
axs[0].yaxis.set_ticks_position("left")
axs[0].yaxis.set_label_position("left")

for i in range(100):
    axs[1].axhline(log_values_2[i], color="red")
axs[1].set_xticks([])
axs[1].yaxis.set_ticks_position("right")
axs[1].yaxis.set_label_position("right")
axs[1].set_yticks(log_values_2[::-1])
axs[1].set_yticklabels(values_2[::-1])

plt.show()

Yet this code writes the same scale (from values_2) to both left and right subplots. How can create a scale for each subplot?



Solution 1:[1]

What you can do is set both axe separately with your different ticks, and then share the y axis. Something like

import matplotlib.pyplot as plt
import numpy as np


values_1 = range(1,51)
log_values_1 = -np.log(values_1)

values_2 = range(1,101)
log_values_2 = -np.log(values_2)

fig, axs = plt.subplots(1, 2, figsize=(10,20) )

for i in range(50):
    axs[0].axhline(log_values_1[i], color="blue")
for i in range(100):
    axs[1].axhline(log_values_2[i], color="red") 
axs[0].set_yticks(log_values_1[::-1],[str(v) for v in values_1[::-1]]) 
axs[0].yaxis.set_ticks_position("left")
axs[0].yaxis.set_label_position("left")

axs[1].set_xticks([])
axs[1].yaxis.set_ticks_position("right")
axs[1].yaxis.set_label_position("right")
axs[1].set_yticks(log_values_2[::-1],[str(v) for v in values_2[::-1]] ) 
axs[0].get_shared_y_axes().join(axs[0], axs[1])
axs[0].autoscale()
plt.show()

I'm not sure you will end up with the output you wanted though

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1