gpt4 book ai didi

python - 更改 matplotlib 中日期时间轴的格式

转载 作者:太空宇宙 更新时间:2023-11-03 21:22:54 25 4
gpt4 key购买 nike

我有一个索引为datetime的系列,我希望绘制它。我想在 y 轴上绘制系列的值,在 x 轴上绘制系列的索引。 系列如下所示:

2014-01-01     7
2014-02-01 8
2014-03-01 9
2014-04-01 8
...

我使用 plt.plot(series.index, series.values) 生成图表。但图表看起来像:

graph

问题是我只想输入年份和月份(yyyy-mm 或 2016 年 3 月)。但是,该图表包含小时、分钟和秒。如何删除它们以获得所需的格式?

最佳答案

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

# sample data
N = 30
drange = pd.date_range("2014-01", periods=N, freq="MS")
np.random.seed(365) # for a reproducible example of values
values = {'values':np.random.randint(1,20,size=N)}
df = pd.DataFrame(values, index=drange)

fig, ax = plt.subplots()
ax.plot(df.index, df.values)
ax.set_xticks(df.index)

# use formatters to specify major and minor ticks
ax.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m"))
ax.xaxis.set_minor_formatter(mdates.DateFormatter("%Y-%m"))
_ = plt.xticks(rotation=90)

enter image description here

关于python - 更改 matplotlib 中日期时间轴的格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54101394/

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