How to eliminate the diagonal line that appears when I run my script using pandas and matplotlib?

Viewed 136

I have come across this similar situation: matplotlib plot shows an unnecessary diagonal line however, it didn't help me since I produce my plot from a csv file, not a data array. Here's my code:

import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv(r"C:\Users\HP\OneDrive\Desktop\MPGES-1\Computational_work\MD\rmsd-yeni-utf-modifiye.csv", sep=";")

df.plot(kind="line", color="red", title="rmsd", xlabel="time", ylabel="freq")

plt.plot(df)
plt.show()

I attach the graph and the screenshot of the beginning of the csv file.

graph screenshot-csv file

Shortly, I only want to eliminate the diagonal line seen in the picture as the rest of the graph seems to be fine.

Thanks,

1 Answers

Pandas read_csv is inferring a header row from your csv file and is plotting x/y columns incorrectly in your example.

As your csv file does not have a header row you can use set the names like below to define one during import and use the column names to plot x='time', y='freq'

import matplotlib.pyplot as plt
import pandas as pd
    
df = pd.read_csv(r"C:\Users\HP\OneDrive\Desktop\MPGES-1\Computational_work\MD\rmsd-yeni-utf-modifiye.csv", sep=";", names=['time', 'freq'])
df.plot(kind="line", color="red", title="rmsd", xlabel="time", ylabel="freq", x='time', y='freq')

plt.show()

Alternatively you can set header=None when reading the csv and use the indexes for plotting x=0,y=1

df = pd.read_csv(r"C:\Users\HP\OneDrive\Desktop\MPGES-1\Computational_work\MD\rmsd-yeni-utf-modifiye.csv", sep=";", header=None)
df.plot(kind="line", color="red", title="rmsd", xlabel="time", ylabel="freq",x=0,y=1)
plt.show()

Or as a third fix you could consider adding a header row to your dataset

enter image description here

and plot letting pandas use the first row as header for column names

df = pd.read_csv(r"C:\Users\HP\OneDrive\Desktop\MPGES-1\Computational_work\MD\rmsd-yeni-utf-modifiye.csv", sep=";")
df.plot(kind="line", color="red", title="rmsd", xlabel="time", ylabel="freq",x="time",y="freq")
plt.show()

example plot using different data enter image description here

https://pandas.pydata.org/docs/reference/api/pandas.read_csv.html

Related