Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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}")
    axes[i].legend()

plt.show()

which results in:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

enter image description here

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

data.plot()
plt.show()

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading