簡體   English   中英

如何為 Seaborn displot 指定日期 bin 范圍

[英]How to specify date bin ranges for Seaborn displot

問題陳述

我正在創建從 1870 年開始的每N年期間洪水事件的分布 plot。我正在使用 Pandas 和 Seaborn。 我需要幫助...

  1. 使用sns.displot時指定每個 bin 的日期范圍,以及
  2. 清楚地代表我沿x軸的 bin 大小規格。

為了澄清這個問題,這里是我正在使用的數據、我嘗試過的數據以及對所需 output 的描述。

數據

我使用的數據可從美國氣象服務獲得。

import pandas as pd
import bs4
import urllib.request
link = "https://water.weather.gov/ahps2/crests.php?wfo=jan&gage=jacm6&crest_type=historic"

webpage=str(urllib.request.urlopen(link).read())
soup = bs4.BeautifulSoup(webpage)

tbl = soup.find('div', class_='water_information')
vals = tbl.get_text().split(r'\n')

tcdf = pd.Series(vals).str.extractall(r'\((?P<Rank>\d+)\)\s(?P<Stage>\d+.\d+)\sft\son\s(?P<Date>\d{2}\/\d{2}\/\d{4})')\
    .reset_index(drop=True)

tcdf['Stage'] = tcdf.Stage.astype(float)
total_crests_events = len(tcdf)
tcdf['Rank'] = tcdf.Rank.astype(int)
tcdf['Date'] = pd.to_datetime(tcdf.Date)

什么有效

我可以使用 Seaborn 的displot對數據進行 plot 處理,並且可以使用bins命令來操作 bin 的數量。

第二張圖片更接近我想要的 output。 但是,我認為垃圾箱的開始和結束位置並不明確。 例如,前兩個分檔(從左到右閱讀)清楚地開始於 1880 年之前和結束於 1880 年之后,但確切的年份並不清楚。

import seaborn as sns
# fig. 1: data distribution using default bin parameters
sns.displot(data=tcdf,x="Date")
# fig. 2: data distribution using 40 bins
sns.displot(data=tcdf,x="Date",bins=40)

使用默認 bin 參數的數據分布 在此處輸入圖像描述

什么失敗了

我嘗試使用bins輸入指定日期范圍。 該方法松散地基於先前的 SO 線程

my_bins = pd.date_range(start='1870',end='2025',freq='5YS')
sns.displot(data=tcdf,x="Date",bins=my_bins)

但是,這種嘗試產生了 TypeError

TypeError: Cannot cast array data from dtype('O') to dtype('float64') according to the rule 'safe'

這是一個很長的問題,所以我想可能有必要進行一些澄清。 請不要猶豫,在評論中提問。

提前致謝。

Seaborn 在內部將其輸入數據轉換為數字,以便對其進行數學運算,並使用 matplotlib 的“單位轉換”機制來做到這一點。 因此,傳遞有效的 bin 的最簡單方法是使用 matplotlib 的日期轉換器:

sns.displot(data=tcdf, x="Date", bins=mpl.dates.date2num(my_bins))

在此處輸入圖像描述

暫無
暫無

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

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