Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pyplot: Shared x-axis, how to shift individual ytick labels?

I would like to plot two datasets sharing the same x-axis, like so:

import numpy as np
import matplotlib.pyplot as plt

diagramm,axes=plt.subplots(nrows=2,sharex='col',gridspec_kw={'hspace': 0, 'wspace': 0})
axes[1].set_xlim([0,10])

axes[0].set_ylim(-1.0,1.0)
axes[1].set_ylim(-0.01,0.01)

xval=np.linspace(0,10,100)

axes[0].plot(xval,np.sin(xval), color="red")
axes[1].plot(xval,0.01*np.sin(xval), color="blue")

plt.show()

The result is the following:

enter image description here

You see the problem: The lowest/highest ytick labels of the upper/lower plot are overprinted on each other. How can I shift these labels up/down, so that they are both readable?

(Note: Obviously, I could add hspace or change the limits to, e.g., -1.1 and 0.011. However, I would prefer shifting the tick labels, if possible.)

like image 541
Toffomat Avatar asked Dec 14 '25 03:12

Toffomat


1 Answers

Following this answer to a related question, you could manually move the two labels a bit:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.transforms import ScaledTranslation

diagramm,axes=plt.subplots(nrows=2,sharex='col',gridspec_kw={'hspace': 0, 'wspace': 0})
axes[1].set_xlim([0,10])

axes[0].set_ylim(-1.0,1.0)
axes[1].set_ylim(-0.01,0.01)

xval=np.linspace(0,10,100)

axes[0].plot(xval,np.sin(xval), color="red")
axes[1].plot(xval,0.01*np.sin(xval), color="blue")

# Provide offset: 5pt=5/72inch vertically
offset = ScaledTranslation(0, 5/72, diagramm.dpi_scale_trans)
# Move upper label up
l = axes[0].yaxis.get_majorticklabels()[0]
l.set_transform(l.get_transform() + offset)
# Move lower label down
l = axes[1].yaxis.get_majorticklabels()[-1]
l.set_transform(l.get_transform() - offset)

plt.show()

For me, this produces: plot with adjusted labels

like image 51
simon Avatar answered Dec 15 '25 23:12

simon



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!