日期格式的X轴格式化

2 投票
1 回答
9998 浏览
提问于 2025-04-18 03:44

我写了一段代码,可以绘制用户选择的股票在过去七天的股价变化情况。现在我遇到的问题是,我想把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()

1 个回答

5

当你使用你的方法绘制数据时,其实是在把你的 y 数据和一些数字(浮点数)在 x 轴上进行对比,比如 20140421.0(我猜这代表的是2014年4月21日这个日期)。

你需要把这些浮点数转换成 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

示例

撰写回答