在seaborn中修改x轴刻度标签

7

我想修改x轴刻度标签的格式为日期格式(%m-%d)。

我的数据包含一段时间内的每小时数据值。我正在尝试绘制14天的数据,但是当我运行时,x标签完全混乱。

enter image description here

是否有办法仅显示日期并跳过x轴上的小时值? 是否有办法修改x轴刻度,在其中我可以跳过小时标签,并仅显示日期标签?我正在使用seaborn。

在i的评论建议下,我编辑了我的代码以绘制如下图:

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"))

但是我收到了以下错误:

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()

我检查了日期时间列,并得到了以下数据类型的输出:

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]

我怀疑x轴的刻度问题,所以运行g.get_xticks()(获取x轴刻度)时,输出结果为序数。有人能告诉我这是为什么吗?

1个回答

10

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()

以下是数据框信息

enter image description here

绘制图形

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

输出:

在此输入图像描述

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

如果您要绘制条形图,则以上方法存在问题。 因此,将使用以下代码。

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()

输出:

此处输入图片描述


当我执行时,我遇到了以下错误:'DateFormatter发现x = 0的值,这是一个非法日期;这通常是因为您没有告知轴它正在绘制日期,例如使用ax.xaxis_date()'。 - Naveen Gabriel
意味着x值不是datetime对象。您可以将x列转换为datetime对象,如pd.to_datetime(df["xaxis"]) - Narendra Prasath
我的数据框列肯定是日期时间对象类型。 - Naveen Gabriel
@NaveenGabriel 是的,我也遇到了同样的问题。因此,我已经更新了条形图的解决方案。请检查更新后的解决方案。如果它对你有用,请点赞。谢谢。 - Narendra Prasath
@NaveenGabriel,希望更新的解决方案对您有用。 - Narendra Prasath
显示剩余5条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接