Home > Backend Development > Python Tutorial > How to Convert Non-Standard Date Formats for Plotting in Python?

How to Convert Non-Standard Date Formats for Plotting in Python?

Patricia Arquette
Release: 2024-10-17 13:48:30
Original
481 people have browsed it

How to Convert Non-Standard Date Formats for Plotting in Python?

Converting Dates to Plottable Format

Plotting data against dates can be challenging when dates are stored in non-standard formats. In the given case, the date format is "01/02/1991". To simplify the plotting process, we can convert these dates into a format acceptable by the plot function of matplotlib.

To begin, convert the strings into instances of Python datetime.date:

<code class="python">import datetime as dt

dates = ['01/02/1991','01/03/1991','01/04/1991']
x = [dt.datetime.strptime(d,'%m/%d/%Y').date() for d in dates]</code>
Copy after login

The next step is to plot the data. Instead of using plot_date(), which encountered the error, we can use the simpler plot() instead:

<code class="python">import matplotlib.pyplot as plt
import matplotlib.dates as mdates

plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m/%d/%Y'))
plt.gca().xaxis.set_major_locator(mdates.DayLocator())
plt.plot(x,y)
plt.gcf().autofmt_xdate()</code>
Copy after login

By following these steps, you can now plot your information effectively against dates in the desired format.

The above is the detailed content of How to Convert Non-Standard Date Formats for Plotting in Python?. For more information, please follow other related articles on the PHP Chinese website!

source:php
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