首页  >  文章  >  后端开发  >  如何在 Pandas 线图的 x 轴上正确显示日期?

如何在 Pandas 线图的 x 轴上正确显示日期?

Patricia Arquette
Patricia Arquette原创
2024-10-26 18:49:02693浏览

How to Correctly Display Dates on the x-axis of a Pandas Line Plot?

在 Pandas 数据框线图的 x 轴上显示日期

简介

要在 Pandas 线图的 x 轴上显示日期,set_index () 方法可用于将包含日期值的列转换为 DataFrame 的索引。但是,当使用 matplotlib 的 DateFormatter 函数格式化日期时,可能会出现某些问题。

DateFormatter 问题

下图说明了在代码中添加 DateFormatter 时出现的问题:

[日期格式不正确的线图图像]

请注意,日期从 5-24 开始,而不是 5-25,并且星期四被错误地标记为 2017 年的 5-25。这通常是由于时区 - pandas 和 matplotlib 日期时间实用程序之间的相关问题或不兼容性。

Pandas 和 Matplotlib 日期时间对象不兼容

Pandas 和 matplotlib 日期时间对象通常不兼容。当尝试在使用 pandas 创建的日期轴上使用 matplotlib 日期对象时,可能会出现问题。

造成这种情况的一个原因是 pandas 日期时间对象被转换为浮点数,表示自 0001-01 以来的天数-01 UTC,加 1。此格式与 matplotlib 的日期时间格式不同。

解决方案

使用 x_compat

要解决日期格式问题,可以使用 x_compat=True 参数传递给plot()方法。这指示 pandas 不要使用自己的日期时间格式,从而允许使用 matplotlib 的股票代码、定位器和格式化程序。

使用 Matplotlib 绘制日期时间

或者,如果需要更精确的日期时间格式,matplotlib可用于绘图和格式化。以下代码片段演示了这种方法:

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

# Create the DataFrame
df = pd.DataFrame({'date':['20170527','20170526','20170525'],'ratio1':[1,0.98,0.97]})
df['date'] = pd.to_datetime(df['date'])

# Create the line plot
plt.plot(df['date'], df['ratio1'])

# Set major locator and formatter for the x-axis
plt.gca().xaxis.set_major_locator(dates.DayLocator())
plt.gca().xaxis.set_major_formatter(dates.DateFormatter('%d\n\n%a'))

# Invert the x-axis for chronological order
plt.gca().invert_xaxis()

# Autofmt the x-axis for optimal placement of dates
plt.gcf().autofmt_xdate(rotation=0, ha="center")

# Display the plot
plt.show()</code>

此修订后的代码将生成一个线图,其中 x 轴上的日期格式准确。

以上是如何在 Pandas 线图的 x 轴上正确显示日期?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn