修改seaborn中的x刻度标签

Nav*_*iel 4 python data-visualization seaborn

我正在尝试将 x-tick 标签的格式修改为日期格式 (%m-%d)。

我的数据由特定日期期间的每小时数据值组成。我正在尝试绘制 14 天的数据。但是,当我运行时,我得到的 x 标签完全混乱。

在此处输入图片说明

有什么办法可以只显示日期并跳过 x 轴上的每小时值。? 有什么方法可以修改 x 刻度,我可以跳过几个小时的标签并只显示日期的标签?我正在使用seaborn。

根据评论的建议,我编辑了我的代码以绘制如下:

fig, ax = plt.pyplot.subplots()
g = sns.barplot(data=data_n,x='datetime',y='hourly_return')
g.xaxis.set_major_formatter(plt.dates.DateFormatter("%d-%b"))
Run Code Online (Sandbox Code Playgroud)

但我收到以下错误:

ValueError: DateFormatter found a value of x=0, which is an illegal 
date; this usually occurs because you have not informed the axis that 
it is plotting dates, e.g., with ax.xaxis_date()
Run Code Online (Sandbox Code Playgroud)

在检查 datetime 列时,我得到以下带有列数据类型类型的输出:

0     2020-01-01 00:00:00
1     2020-01-01 01:00:00
2     2020-01-01 02:00:00
3     2020-01-01 03:00:00
4     2020-01-01 04:00:00
          ...        
307   2020-01-13 19:00:00
308   2020-01-13 20:00:00
309   2020-01-13 21:00:00
310   2020-01-13 22:00:00
311   2020-01-13 23:00:00
Name: datetime, Length: 312, dtype: datetime64[ns]
Run Code Online (Sandbox Code Playgroud)

我怀疑 x 刻度,所以当我运行g.get_xticks()[它获取 x 轴上的刻度] 时,我得到的输出是序数。谁能告诉为什么会这样?

Nar*_*ath 6

1. 用 x 轴日期时间绘制线图的方法

您可以尝试更改 x 轴格式,如下所示

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib import dates

## create dummy dataframe
datelist = pd.date_range(start='2020-01-01 00:00:00', periods=312,freq='1H').tolist()
#create dummy dataframe
df = pd.DataFrame(datelist, columns=["datetime"])
df["val"] = [i for i in range(1,312+1)]
df.head()
Run Code Online (Sandbox Code Playgroud)

以下是数据框信息

在此处输入图片说明

画图

fig, ax = plt.subplots()
chart = sns.lineplot(data=df, ax=ax, x="datetime",y="val")
ax.xaxis.set_major_formatter(dates.DateFormatter("%d-%b"))
Run Code Online (Sandbox Code Playgroud)

输出:

在此处输入图片说明

2. 使用带有 x 轴日期时间的 seaborn 绘制条形图的方法

如果您为条形图绘制,则上述方法存在问题。所以,将使用下面的代码

fig, ax = plt.subplots()
## barplot
chart = sns.barplot(data=df, ax=ax,x="datetime",y="val")

## freq of showing dates, since frequency of datetime in our data is 1H. 
## so, will have every day 24data points
## Trying to calculate the frequency by each day 
## (assumed points are collected every hours in each day, 24)
## set the frequency for labelling the xaxis
freq = int(24)
# set the xlabels as the datetime data for the given labelling frequency,
# also use only the date for the label
ax.set_xticklabels(df.iloc[::freq]["datetime"].dt.strftime("%d-%b-%y"))
# set the xticks at the same frequency as the xlabels
xtix = ax.get_xticks()
ax.set_xticks(xtix[::freq])
# nicer label format for dates
fig.autofmt_xdate()

plt.show()
Run Code Online (Sandbox Code Playgroud)

输出:

在此处输入图片说明