Home >Backend Development >Python Tutorial >How to Plot a DataFrame with a DateTime Index in Matplotlib?

How to Plot a DataFrame with a DateTime Index in Matplotlib?

Susan Sarandon
Susan SarandonOriginal
2024-11-10 22:36:03717browse

How to Plot a DataFrame with a DateTime Index in Matplotlib?

Adding a New Column with Pandas

Problem: When plotting a DataFrame with matplotlib, an error is encountered due to the index column being a datetime value.

Solution: To resolve this, a new column must be added that replicates the index column. This cloned column can then be used for plotting.

Implementation:

  1. Reset the DataFrame's index:
df3 = df3.reset_index()
  1. Create a new column:
df3['Time'] = df3.index

Alternatively, you can create the new column without resetting the index:

df3['new'] = df3.index
  1. Plot the data:
plt.plot(df3['magnetic_mag mean'], df3['Time'], label='FDI')

Additional Tips:

  • Instead of creating a new column, you can also pd.to_datetime(df3.index) and assign it to a new variable to preserve the index as a datetime object.
  • Improved code for reading the CSV file:
df = pd.read_csv('university2.csv', 
                 sep=";", 
                 skiprows=1,
                 index_col='YYYY-MO-DD HH-MI-SS_SSS',
                 parse_dates=True)

The above is the detailed content of How to Plot a DataFrame with a DateTime Index in Matplotlib?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn