'Same x-ticks for all subplots in matplotlib

Though this question has already been asked, but I am unable to implement that. I don't know how get the xticks for each subplot and then replace it with the new one. The other problem is that in every subplot number of xticks labels are different.
I have this dummy data

Fs = 8000
f = 50
sample = 8000
x = np.arange(sample)
y = np.sin(2 * np.pi * f * x / Fs)

I have implemented discrete wavelet transform at it.

coefs = pywt.wavedec(y, wavelet='db4', level=None)
len(coefs)
fig,ax=plt.subplots(nrows=8,ncols=1,figsize=(8,10))
label=['cA','cD6','cD5','cD4','cD3','cD2','cD1']
for i,l in zip(range(8),label):
  ax[0].plot(y,color='b')
  ax[0].set_xticks([],[1,2,3,4,5,6,7,8])
  ax[0].set_title('EEG',x=-0.1,y=0.1)
  ax[i+1].plot(coefs[i-1],color='b')
  ax[i+1].set_title(l,x=-0.1,y=0.1)

It plots the following image. What I want is the same x-axis ticks range from 0-8 for all subplots enter image description here



Solution 1:[1]

I may suggest to bring your data to the same scale in order to use shared x axis, as shown bellow.

import matplotlib.pyplot as plt
import numpy as np
import pywt

Fs = 8000
f = 50
sample = 8000

x = np.arange(sample)
y = np.sin(2 * np.pi * f * x / Fs)

coefs = pywt.wavedec(y, wavelet='db4', level=None)

fig, ax = plt.subplots(nrows=8, ncols=1, figsize=(8,10), sharex=True)

label=['cA','cD6','cD5','cD4','cD3','cD2','cD1']

for i, l in zip(range(8),label):
    ax[0].plot(y[:9], color='b')             # << bring the data to one scale with slice [:9]
    ax[0].set_title('EEG', x=-0.1, y=0.1)
    
    ax[i+1].plot(coefs[i-1][:9], color='b')  # << bring the data to one scale with slice [:9]
    ax[i+1].set_title(l, x=-0.1, y=0.1)

plt.show()

Returns

enter image description here

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 gremur