gpt4 book ai didi

python - 如何在 matplotlib 中设置日期的 xticklabels

转载 作者:太空狗 更新时间:2023-10-30 00:44:33 25 4
gpt4 key购买 nike

我正在尝试绘制两个列表中的值。 x 轴值是日期。到目前为止尝试过这些东西

year = [20070102,20070806,20091208,20111109,20120816,20140117,20140813]
yvalues = [-0.5,-0.5,-0.75,-0.75,-0.5,-1.25,-1.25]

dates = [datetime.datetime.strptime(str(int(date)),'%Y%m%d') for date in year]

fig, axes = plt.subplots(1, 1, figsize=(16, 9), dpi=100)

line1, = axes.plot(dates,yvalues, lw=2, marker='*', color='r')
axes.legend([line1],['VALUES'],loc=1)
axes.grid()
axes.set_xlabel('YEAR')
axes.set_ylabel('VALUES')

yticks = [-2.0,-1.75,-1.5,-1.25,-1.0,-0.75,-0.5,-0.25,0.0]
axes.set_yticks(yticks)
axes.set_yticklabels(["$%.2f$" % y for y in yticks]);

axes.set_xticks(dates)
#axes.set_xticklabels()

这个数字看起来不错。但无法正确标记 x 轴刻度。我试图用 2007-01-02 或 2007 年一月之类的东西来标记 x 轴。

提前致谢

最佳答案

您可以使用 DateFormater 控制日期格式:

import matplotlib.dates as mdates
xfmt = mdates.DateFormatter('%Y-%m-%d')
axes.xaxis.set_major_formatter(xfmt)

import datetime as DT
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

year = [20070102,20070806,20091208,20111109,20120816,20140117,20140813]
yvalues = [-0.5,-0.5,-0.75,-0.75,-0.5,-1.25,-1.25]

dates = [DT.datetime.strptime(str(int(date)),'%Y%m%d') for date in year]

fig, axes = plt.subplots(1, 1, figsize=(16, 9), dpi=100)

line1, = axes.plot(dates,yvalues, lw=2, marker='*', color='r')
axes.legend([line1],['VALUES'],loc=1)
axes.grid()
axes.set_xlabel('YEAR')
axes.set_ylabel('VALUES')

yticks = [-2.0,-1.75,-1.5,-1.25,-1.0,-0.75,-0.5,-0.25,0.0]
axes.set_yticks(yticks)
axes.set_yticklabels(["$%.2f$" % y for y in yticks]);

xfmt = mdates.DateFormatter('%Y-%m-%d')
axes.xaxis.set_major_formatter(xfmt)
axes.set_xticks(dates)
plt.xticks(rotation=25)
plt.show()

产量

enter image description here

关于python - 如何在 matplotlib 中设置日期的 xticklabels,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28385184/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com