簡體   English   中英

修改 seaborn 中的 x 刻度標簽

[英]Modifying x ticks labels in seaborn

我正在嘗試將 x-tick label 的格式修改為日期格式 (%m-%d)。

我的數據包含特定日期期間的每小時數據值。 我正在嘗試 plot 數據 14 天。 但是,當我運行時,x 標簽完全混亂了。

在此處輸入圖像描述

有什么方法可以只顯示日期並跳過 x 軸上的每小時值。 有什么方法可以修改 x 刻度,我可以跳過幾個小時的標簽並只顯示日期的標簽? 我正在使用 seaborn。

在收到評論的建議后,我將我的代碼編輯為 plot,如下所示:

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

檢查日期時間列后,我得到以下 output 以及該列的數據類型:

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 軸上的刻度] 時,我得到 output 作為序數。 誰能說出為什么會這樣?

1. 用 x 軸日期時間畫線 Plot 的方法

您可以嘗試如下更改 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()

下面是dataframe的信息

在此處輸入圖像描述

抽獎plot

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

Output:

在此處輸入圖像描述

2. 使用帶 x 軸日期時間的 seaborn 繪制條形圖 plot 的方法

如果您繪制條形圖,則上述方法存在問題。 所以,將使用下面的代碼

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

output:

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM