gpt4 book ai didi

python - 修改日期的主要和次要 xticks

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

我正在绘制两个 pandas 系列。索引是一个日期(1-1到12-31)

s1.plot()
s2.plot()

pd.plot() 解释日期并将它们分配给轴值,如下所示:

enter image description here

我想将主要刻度修改为每个月的第一天,将次要刻度修改为中间的日子

这个有效:

%matplotlib notebook

import matplotlib as mpl
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
import pandas as pd

df = pd.read_csv('data.csv')

df['Date'] = pd.to_datetime(df['Date']).dt.strftime('%m-%d')
s2014max = df2014.groupby(['Date'], sort=True)['Data_Value'].max()/10
s2014min = df2014.groupby(['Date'], sort=True)['Data_Value'].min()/10

#remove the leap day and convert to datetime for plotting
s2014min = s2014min[s2014min.index != '02-29']
s2014max = s2014max[s2014max.index != '02-29']
dateslist = s2014min.index.tolist()

dates = [pd.datetime.strptime(date, '%m-%d').date() for date in dateslist]

plt.figure()

ax = plt.gca()
ax.xaxis.set_major_locator(mdates.MonthLocator())
ax.xaxis.set_minor_locator(mdates.DayLocator())

monthFmt = mdates.DateFormatter('%b')
dayFmt = mdates.DateFormatter('%d')
ax.xaxis.set_major_formatter(monthFmt)
ax.xaxis.set_minor_formatter(dayFmt)
ax.tick_params(direction='out', pad=15)

s2014min.plot()
s2014max.plot()

这导致没有刻度:

enter image description here

最佳答案

一种可能的方法是使用 matplotlib 而不是 pandas 来绘制日期。

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

dates = pd.date_range("2016-01-01", "2016-12-31" )
y = np.cumsum(np.random.normal(size=len(dates)))
df = pd.DataFrame({"Dates" : dates, "y": y})

fig, ax = plt.subplots()
ax.plot_date(df["Dates"], df.y, '-')

ax.xaxis.set_major_locator(mdates.MonthLocator())
ax.xaxis.set_minor_locator(mdates.DayLocator())
monthFmt = mdates.DateFormatter('%b')
ax.xaxis.set_major_formatter(monthFmt)

plt.show()

enter image description here

关于python - 修改日期的主要和次要 xticks,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42880333/

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