gpt4 book ai didi

Pandas 条形图更改日期格式

转载 作者:太空狗 更新时间:2023-10-30 01:36:45 25 4
gpt4 key购买 nike

我有一个简单的堆叠线图,它具有我想要在使用以下代码时神奇地设置的日期格式。

df_ts = df.resample("W", how='max')
df_ts.plot(figsize=(12,8), stacked=True)

enter image description here

但是,在绘制与条形图相同的数据时,日期会神秘地变成一种丑陋且不可读的格式。

df_ts = df.resample("W", how='max')
df_ts.plot(kind='bar', figsize=(12,8), stacked=True)

enter image description here

对原始数据进行了一些转换,使其具有每周最大值。为什么会发生这种自动设置日期的根本变化?我怎样才能得到如上所示格式正确的日期?

这是一些虚拟数据

start = pd.to_datetime("1-1-2012")
idx = pd.date_range(start, periods= 365).tolist()
df=pd.DataFrame({'A':np.random.random(365), 'B':np.random.random(365)})
df.index = idx
df_ts = df.resample('W', how= 'max')
df_ts.plot(kind='bar', stacked=True)

最佳答案

绘图代码假定条形图中的每个条都应该有自己的标签。您可以通过指定自己的格式化程序来覆盖此假设:

ax.xaxis.set_major_formatter(formatter)

Pandas 使用的 pandas.tseries.converter.TimeSeries_DateFormatter当x 值是日期。但是,使用条形图 x 值(至少是那些TimeSeries_DateFormatter.__call__) 收到的仅仅是整数开始为零。如果您尝试将 TimeSeries_DateFormatter 与条形图一起使用,则所有标签都从 Epoch 1970-1-1 UTC 开始,因为这是对应于零的日期。所以不幸的是,用于线图的格式化程序对条形图无用情节(至少据我所知)。

我看到生成所需格式的最简单方法是显式生成和设置标签:

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import matplotlib.ticker as ticker

start = pd.to_datetime("5-1-2012")
idx = pd.date_range(start, periods= 365)
df = pd.DataFrame({'A':np.random.random(365), 'B':np.random.random(365)})
df.index = idx
df_ts = df.resample('W', how= 'max')

ax = df_ts.plot(kind='bar', x=df_ts.index, stacked=True)

# Make most of the ticklabels empty so the labels don't get too crowded
ticklabels = ['']*len(df_ts.index)
# Every 4th ticklable shows the month and day
ticklabels[::4] = [item.strftime('%b %d') for item in df_ts.index[::4]]
# Every 12th ticklabel includes the year
ticklabels[::12] = [item.strftime('%b %d\n%Y') for item in df_ts.index[::12]]
ax.xaxis.set_major_formatter(ticker.FixedFormatter(ticklabels))
plt.gcf().autofmt_xdate()

plt.show()

产量 enter image description here


对于那些寻找带有日期的条形图的简单示例的人:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker

dates = pd.date_range('2012-1-1', '2017-1-1', freq='M')
df = pd.DataFrame({'A':np.random.random(len(dates)), 'Date':dates})
fig, ax = plt.subplots()
df.plot.bar(x='Date', y='A', ax=ax)
ticklabels = ['']*len(df)
skip = len(df)//12
ticklabels[::skip] = df['Date'].iloc[::skip].dt.strftime('%Y-%m-%d')
ax.xaxis.set_major_formatter(mticker.FixedFormatter(ticklabels))
fig.autofmt_xdate()

# fixes the tracker
# https://matplotlib.org/users/recipes.html
def fmt(x, pos=0, max_i=len(ticklabels)-1):
i = int(x)
i = 0 if i < 0 else max_i if i > max_i else i
return dates[i]
ax.fmt_xdata = fmt
plt.show()

enter image description here

关于 Pandas 条形图更改日期格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45610379/

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