Para que los dos subplots compartan el eje x debes especificarlo mediante el argumento sharex
de plt.subplot()
o plt.subplots
.
Además deberás eliminar las marcas y etiquetas del eje x
del segundo subplot, lo que puedes conseguir con Axis.tick_params
.
Para poder eliminar el espaciado entre los dos últimos vas a necesitar usar "grids anidados". Puedes conseguirlo con matplotlib.gridspec.GridSpec
y . matplotlib.gridspec.FromSubplotSpec
.
En cuanto a modificar la lineas, marcadores y línea base de stem, lo que no puedas especificar mediante inefmt
,markerfmt
y basefmt
del constructor puedes hacerlo conservando referencias a cada componente (retornados por stem
) y luego usar matplotlib.pyplot.setp
:
markerline, stemlines, baseline = ax3.stem(
freqs, phase_newdeg, label='Sample name', use_line_collection=True
)
plt.setp(baseline, "color", "purple")
plt.setp(stemlines, 'linestyle', 'dotted')
plt.setp(markerline, "color", "green")
Todo junto:
import matplotlib.pyplot as plt
from matplotlib import gridspec
import numpy as np
t = np.arange(18)
y = np.random.randint(0, 20, 18)
freqs = [-19, -16, -12, -10, -8, -6,-4, -3, 0, 3, 4, 6, 8, 10, 12, 14, 16, 18]
sp = np.array(
[3.14j, 4.14j, 3.18j, 3.20j, 5.14j, 6.14j, 7.10j, 4.5j, 6.10j,
4.3j, 2.4j, 1.18j, 3.7j, 2.12j, 3.14j, 1.4j, 2.17j, 5.1j]
)
phase_newdeg = np.random.randint(0, 20, 18)
gs_gen = gridspec.GridSpec(2, 1, height_ratios=[1, 1.7], hspace=0.3)
gs1 = gridspec.GridSpecFromSubplotSpec(1, 1, subplot_spec=gs_gen[0])
gs2 = gridspec.GridSpecFromSubplotSpec(2, 1, subplot_spec=gs_gen[1])
fig=plt.figure()
ax1 = plt.subplot(gs1[0, 0])
ax2 = plt.subplot(gs2[0, 0])
ax3 = plt.subplot(gs2[1, 0], sharex=ax2)
ax1.plot(t, y, color='red', label='MATHChannel')
ax1.grid(True)
ax1.set_xlabel('time [s]')
ax1.set_ylabel('Amplitude [V]')
ax1.legend(loc='best')
ax2.stem(
freqs, sp.real, markerfmt='x', linefmt='C2-',
label='Re(FFT)', use_line_collection=True
)
ax2.stem(freqs, sp.imag, markerfmt='o', label='Im(FFT)', use_line_collection=True)
ax2.set_xlim(-20,20)
ax2.set_ylabel('Amplitude [V]')
ax2.grid(True)
ax2.legend(loc='best')
ax2.tick_params(
axis='x', which='both', bottom=False, top=False, labelbottom=False
)
ax3.grid(True)
markerline, stemlines, baseline = ax3.stem(
freqs, phase_newdeg, label='Sample name', use_line_collection=True
)
plt.setp(baseline, "color", "purple")
plt.setp(stemlines, 'linestyle', 'dotted')
plt.setp(markerline, "color", "green")
ax3.set_xlim(-20,20)
ax3.set_xlabel('f [Hz]')
ax3.set_ylabel('Phase [deg]')
ax3.legend(loc='best')
plt.subplots_adjust(hspace=.0)
plt.show()
