Dépannage des erreurs de conversion date-heure pour le traçage sur l'axe X

Linda Hamilton
Libérer: 2024-10-17 13:47:02
original
362 Les gens l'ont consulté

Troubleshooting Date-Time Conversion Errors for X-Axis Plotting

Plotting Dates on the X-Axis: A Troubleshooting Guide

When plotting data against dates, it is essential to convert the dates into a format that matplotlib can interpret. However, if you encounter "year is out of range" errors, it indicates an issue with the date conversion process.

Let's address the situation you described:

Problem: Converting dates in "01/02/1991" format results in an error when using plot_date().

Solution:

Instead of using plot_date(), consider using the more straightforward plot() function. To prepare your dates for plotting:

  1. Import Python's datetime library and convert your strings to datetime.date instances:
<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>
Copier après la connexion
  1. Plot the data using plot():
<code class="python">import matplotlib.pyplot as plt
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>
Copier après la connexion

This approach will correctly plot your data against the dates specified on the x-axis, resolving the error you encountered.

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

source:php
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Derniers articles par auteur
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!