2016-01-07 18 views
0

,我有以下數據:如何搭配色彩的傳說和情節的顏色重疊區域地塊在GGPLOT2

head(MP_rates_dateformat) 
     Month repo revrepo bankrate CRR Callrate WPI GDP FED 
1 2001-04-01 9.00 6.75  7 8.0  7.49 5.41 4.6 4.50 
2 2001-05-01 8.75 6.50  7 7.5  8.03 5.60 4.6 4.00 
3 2001-06-01 8.50 6.50  7 7.5  7.24 5.30 4.6 3.75 
4 2001-07-01 8.50 6.50  7 7.5  7.19 5.23 5.3 3.75 
5 2001-08-01 8.50 6.50  7 7.5  6.94 5.41 5.3 3.50 
6 2001-09-01 8.50 6.50  7 7.5  7.30 4.52 5.3 3.00 

我試圖繪製時間序列重疊使用ggplot2變量reporevrepo區地塊。

p2 <- ggplot(MP_rates_dateformat, aes(x= Month)) + geom_area(aes(y=repo, color="repo"), fill="yellowgreen") + geom_area(aes(y=revrepo,color="revrepo"), fill="dodgerblue", alpha=0.7, linetype="dotted") + labs(color="")+ labs(title="Overlapping - Repo & Reverse Repo") 

p2 

enter image description here

我們可以看到傳說是顯示具有相同的顏色填充兩個變量傳奇盒。我希望它能顯示正確的相應顏色,即黃綠色爲repo和dodgerblue爲revrepo

假設我融化數據:

df <- reshape2::melt(MP_rates_dateformat[, c("Month", "repo", "revrepo")], id="Month") 

head(df, 3) 

     Month variable value 
1 2001-04-01  repo 9.00 
2 2001-05-01  repo 8.75 
3 2001-06-01  repo 8.50 

p1 <- ggplot(df, aes(x=Month)) + geom_area(aes(y=value, fill=variable)) + labs(title="Non-Overlapping - Repo & Reverse Repo") 

plot2

但是,這是給我的非重疊區域地塊以正確的傳說....但我要尋找重疊區域的情節。

+0

熔體(蒐集)數據,以便用於回購和revrepo值將下一個變量被收集。將這個變量映射到fill et瞧。 –

回答

0

這是一個基於融化/收集數據的想法的解決方案,使用fill,ggplotposition = "identity"相結合。請注意,列的順序很重要,因爲最小值revrepo應在第一個repo之後繪製。

library("tidyr") 
df_gather <- gather(select(MP_rates_dateformat, 1:3), variable, value, -Month) 

library("ggplot2") 
ggplot(data = df_gather, aes(x = Month)) + 
    geom_area(aes(y = value, fill = variable), position = "identity") 
0

終於明白了!

library("tidyr") 

long_DF<- MP_rates_dateformat[,1:3] %>% gather(variable, value, -Month) 
head(long_DF) 

    Month variable value 
1 2001-04-01  repo 9.00 
2 2001-05-01  repo 8.75 
3 2001-06-01  repo 8.50 
4 2001-07-01  repo 8.50 
5 2001-08-01  repo 8.50 
6 2001-09-01  repo 8.50 

library("ggplot2") 

ggplot(data = long_DF, aes(x = Month)) + 
geom_area(aes(y = value, fill = variable), position = "identity") + labs(fill="") + xlab('\nYears') + ylab('LAF Rates (%)\n') + labs(title="Overlapping - Repo & Reverse Repo\n") 

enter image description here

+0

thnx @Erwan爲解決問題提供一些想法 – Nishant

+0

thnx @Roman爲解決問題提供一些想法 – Nishant

+0

如果有人可以建議我如何將圖的顏色從默認值改爲顏色像'綠色回購'和'revrepo'的dodgerblue – Nishant