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
Release: 2024-11-10 22:36:03
Original
664 people have browsed it

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()
Copy after login
  1. Create a new column:
df3['Time'] = df3.index
Copy after login

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

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

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)
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template