"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Convert Dates to a Numerical Format for Plotting?

How to Convert Dates to a Numerical Format for Plotting?

Published on 2024-11-09
Browse:538

How to Convert Dates to a Numerical Format for Plotting?

Converting Dates to Numerical Format for Plotting

Plotting data against dates can be challenging when the dates are stored in a different format, such as "01/02/1991." This article provides a solution for converting dates into a numerical format that can be easily plotted on the x-axis.

As mentioned in the question, converting the dates using strftime('%Y%m%d') alone may not be sufficient. To resolve this issue, consider using Python's datetime module to convert the strings to instances of datetime.date.

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]

With the dates converted to datetime.date objects, we can proceed to plot using matplotlib.pyplot, as demonstrated in the solution provided.

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()

By following these steps, you can successfully plot data against dates, even when the dates are stored in a non-numerical format.

Release Statement This article is reprinted at: 1729144181 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3