python - 使用日期格式设置 X 轴格式

标签 python date datetime matplotlib plot

我编写了代码,绘制了用户确定的股票市场过去 7 天的股票值(value)随时间变化的情况。 我遇到的问题是我想将 x 轴格式化为 YYMMDD 格式。 我也不明白 x 轴末端的 2.014041e7 是什么意思。

plot

x 的值为:

20140421.0, 20140417.0, 20140416.0, 20140415.0, 20140414.0, 20140411.0, 20140410.0

y 的值为:

531.17, 524.94, 519.01, 517.96, 521.68, 519.61, 523.48

我的代码如下:

mini = min(y)
maxi = max(y)
minimum = mini - 75
maximum = maxi + 75
mini2 = int(min(x))
maxi2 = int(max(x))

plt.close('all')
fig, ax = plt.subplots(1)
pylab.ylim([minimum,maximum])
pylab.xlim([mini2,maxi2])

ax.plot(x, y)
ax.plot(x, y,'ro')
ax.plot(x, m*x + c)
ax.grid()
ax.plot()

最佳答案

使用您的方法绘制数据时,您只需根据 x 中的数字( float )绘制 y 数据,例如 20140421.0 (其中我假设您希望指的是日期 21/04/2014)。

您需要将这些 float 据转换为 matplotlib 能够理解的适当格式。下面的代码获取两个列表 (x, y) 并转换它们。

import numpy as np

import matplotlib.pyplot as plt
import matplotlib.dates as mdates

import datetime as dt

# Original data

raw_x = [20140421.0, 20140417.0, 20140416.0, 20140415.0, 20140414.0, 20140411.0, 20140410.0]
y = [531.17, 524.94, 519.01, 517.96, 521.68, 519.61, 523.48]

# Convert your x-data into an appropriate format.

# date_fmt is a string giving the correct format for your data. In this case
# we are using 'YYYYMMDD.0' as your dates are actually floats.
date_fmt = '%Y%m%d.0'

# Use a list comprehension to convert your dates into datetime objects.
# In the list comp. strptime is used to convert from a string to a datetime
# object.
dt_x = [dt.datetime.strptime(str(i), date_fmt) for i in raw_x]

# Finally we convert the datetime objects into the format used by matplotlib
# in plotting using matplotlib.dates.date2num
x = [mdates.date2num(i) for i in dt_x]

# Now to actually plot your data.
fig, ax = plt.subplots()

# Use plot_date rather than plot when dealing with time data.
ax.plot_date(x, y, 'bo-')

# Create a DateFormatter object which will format your tick labels properly.
# As given in your question I have chosen "YYMMDD"
date_formatter = mdates.DateFormatter('%y%m%d')

# Set the major tick formatter to use your date formatter.
ax.xaxis.set_major_formatter(date_formatter)

# This simply rotates the x-axis tick labels slightly so they fit nicely.
fig.autofmt_xdate()

plt.show()

代码自始至终都带有注释,因此应该很容易解释。有关各个模块的详细信息如下:

  1. datetime
  2. matplotlib.dates

Example

关于python - 使用日期格式设置 X 轴格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23219218/

相关文章:

python - Python 中的优化问题

javascript - 使用 moment 获取日期和当前日期之间的时间差

python - 如何在没有人工交互的情况下使用 Google Drive SDK 2 和 Python 获取 OAuth 凭证

python - Tensorflow:训练神经网络时损失没有改善

mysql - 删除不必要的字符串并更新 MySql 中的日期格式

sql - 减少广泛的查询

php - 将引导日期选择器中的日期插入 MySQL 日期字段不起作用

c# - .NET Compact Framework 上 DateTime.Now 中的毫秒数始终为零?

r - 如何在 R 中将山区标准时间 (MST) 转换为山区夏令时间 (MDT)

python - 如何向 python 子进程添加选项