Python Matplotlib – first plot of "subplots" is slightly off

I’m facing a weird issue with Matplotlib’s subplots() method. I’ve got a Pandas Dataframe I want to plot that has 4 columns.

One option is to plot each column in a separate axis using plt.subplots():

import matplotlib.pyplot as plt
import pandas as pd

data = pd.read_csv("data.csv", sep="\t")

fig, axes = plt.subplots(4, 1, sharex=True)
for i, c in enumerate(data.columns):
    axes[i].plot(data[c], label=f"{c}")

which results in:

enter image description here

However, if I simply call plot() on the Dataframe directly:


I get this result:
enter image description here

Why does the first plot look slightly off compared to the other three when using plt.subplots(), whereas it looks perfectly aligned according to pd.DataFrame.plot()? Which one should I trust?

>Solution :

The range of your y-axis is very small on the first subplot, between -0.5 to 0.5, compared to the range on the other subplots [-20;20]. That would explain why you don’t see the shift when you plot the dataframe directly. There is no incompatibility here between your 2 plotting methods as far as I can tell.

Leave a Reply