[英]Percentage of bin total on y-axis with facet_wrap and time series on x-axis
我正在調查一個數據集,其中包含Prosper的貸款信息,特別是投資者的行為。
我要創建的圖將在y軸上顯示投資者,在x軸上顯示時間,將其歸為平均月份。 信用等級也將面臨這一問題。 最終,我希望每個bin都能顯示每個計算月(或實際月份,但計算起來更容易進行分類)分配給每個Credit Grade(構面變量)的總投資者百分比。
我已經嘗試過..density..
, sum(..count..)
..count..
/ sum(..count..)
, geom_density
等,並且看到了很多帖子,它們將每個構面總計為1或將整個圖總計為1。我試圖將所有方面中的每個bin求和為1。我也希望直接在ggplot中做到這一點,而不是更改數據框,但我將盡我所能。
以下代碼顯示了兩種顯示投資者數量的方法(每倉位數和每倉位占整個地塊的百分比):
t1 <- ggplot(data = loans, aes(x=as.POSIXct(strptime(LoanOriginationDate, '%Y-%m-%d %H:%M:%S')))) +
geom_histogram(binwidth = 60*60*24*30.4375, aes(y = ..count../sum(..count..), group = Investors)) +
facet_wrap(~ProsperCreditGrade) +
scale_y_continuous()
t2 <- ggplot(loans,aes(x=as.POSIXct(strptime(LoanOriginationDate, '%Y-%m-%d %H:%M:%S')),fill=ProsperCreditGrade))+
geom_histogram(aes(y=2629800* ..count../sum(..count..)),
alpha=1,position='identity',binwidth=2629800) +
facet_wrap(~ProsperCreditGrade) +
stat_bin(aes(y = ..density..))
grid.arrange(t1,t2,ncol=1)
正如您在圖中所看到的,在數據集涵蓋的時間結束時,總投資者增加了很多。 這並未顯示在給定時間內的相對投資行為,這就是我要調查的內容。
我還能嘗試什么?
在Udacity.com的Stephen和dplyr
幫助下,最終代碼如下:
loans$month <- month(as.POSIXct((round(as.numeric(as.POSIXct(loans$LoanOriginationDate))/2629800)*2629800), origin = "1969-12-31 19:00:00"))
loans$year <- year(as.POSIXct((round(as.numeric(as.POSIXct(loans$LoanOriginationDate))/2629800)*2629800), origin = "1969-12-31 19:00:00"))
loans$calculatedMonth <- ((loans$year-2005)*12)+loans$month
loanInvestors <- loans %>% group_by(calculatedMonth, ProsperCreditGrade) %>% summarise (n = n()) %>% mutate(proportion = n / sum(n))
ggplot(data = loanInvestors, aes(x = calculatedMonth, y = proportion, fill = proportion, width = 3)) +
geom_bar(stat = "identity") + facet_wrap(~ProsperCreditGrade) +
scale_y_sqrt() + geom_smooth(color = "red") +
scale_fill_gradient()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.