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.
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