[英]Matplotlib/Seaborn - Plotting datetime objects on the x-axis is giving a very long label
我正在嘗試使用 Seaborn 獲取 plot 時間序列數據,但是 x 軸刻度標簽的格式非常奇怪,提供了比我感興趣的更多的細節。這是我的 dataframe 的頭部,我的代碼,和 output。
Dataframe 的頭部顯示要合並的年月列:
df['arrival'] = pd.to_datetime(df['arrival_date_month'] + ' ' + df['arrival_date_year'])
fig, ax = plt.subplots(figsize=(15,8))
count_plot = sns.countplot(x='arrival',data=df,hue='hotel',palette='rocket')
for ind, label in enumerate(count_plot.get_xticklabels()):
if ind % 3 == 0:
label.set_visible(True)
label.set_rotation(45)
else:
label.set_visible(False)
ax.legend(title = 'Type of Hotel')
ax.set_xlabel('Month')
ax.set_ylabel('Number of Reservations')
為什么 x 軸刻度標簽如此具體? 如果我運行 df['arrival'],我會得到以下信息:
在 pandas 中,所有日期時間對象都存儲為datetime64[ns]
,精確到納秒。 當你運行df['arrival']
時,你得到的 output 是正在顯示的內容,但下面的實際基礎數據是納秒精度的(這就是 matplotlib 在 x-ticks 上顯示的內容)。
我最初建議使用 matplotlib mdates.DateFormatter
方法來解決此問題,但它很挑剔並且似乎無法解釋日期時間( 這個問題提出了與 matplotlib dateformatter 類似的問題)。
因此,我建議在創建 sns.countplot 之前將'arrival'
列轉換為 df 中的日期時間字符串:
df['arrival'] = df['arrival'].dt.strftime('%Y-%m-%d')
這是一個小例子:
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
df = pd.DataFrame({
'hotel': ['Resort Hotel']*10 + ['City Hotel']*10,
'arrival': list(pd.date_range('2015-07-01','2015-07-10'))*2
})
df['arrival'] = df['arrival'].dt.strftime('%Y-%m-%d')
fig, ax = plt.subplots(figsize=(15,8))
count_plot = sns.countplot(x='arrival',data=df,hue='hotel',palette='rocket')
for ind, label in enumerate(count_plot.get_xticklabels()):
if ind % 3 == 0:
label.set_visible(True)
label.set_rotation(45)
else:
label.set_visible(False)
ax.legend(title = 'Type of Hotel')
ax.set_xlabel('Month')
# ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
ax.set_ylabel('Number of Reservations')
plt.show()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.