2016-01-01 204 views
3

我似乎無法在ggplot2中設置功能區來顯示。ggplot2中缺少功能區

這裏有一個由數據集:

> GlobalDFData 
    Estimate Upper Lower Date Area 
1  100 125 75 Q1_16 Global 
2  125 150 100 Q2_16 Global 
3  150 175 125 Q3_16 Global 
4  175 200 150 Q4_16 Global 

下面是我沒有成功嘗試的代碼。我得到的折線圖,但沒有上限和下限

ggplot(GlobalDFData, aes(x = Date)) + 
    geom_line(aes(y = Estimate, group = Area, color = Area))+ 
    geom_point(aes(y = Estimate, x = Date))+ 
    geom_ribbon(aes(ymin = Lower, ymax = Upper)) 

回答

5

geom_ribbon喜歡連續的x值,但是你可以通過在通話過程中提供一個欺騙了一點。

plt <- ggplot(dat, aes(x = Date)) + 
geom_line(aes(y = Estimate, group = Area, color = Area)) + 
geom_point(aes(y = Estimate, x = Date)) 
plt + geom_ribbon(aes(x = 1:length(Date), ymin = Lower, ymax = Upper), alpha = .2) 

enter image description here 此外,你可以使用geom_linerange,但可能不會達到你要的樣子:

plt + geom_linerange(aes(ymin = Lower, ymax = Upper, color = Area)) 

enter image description here

而且奇怪的是,分配一個顏色與geom_ribbon達到相同(有效)的結果(繪圖未顯示):

plt + geom_ribbon(aes(ymin = Lower, ymax = Upper, color = Area)) 

此外,您可以使用zoo包到您的季度倍scale_x_yearqtr轉換的東西,可以理解爲連續的,結合:

library(zoo) 

dat$Date <- as.yearqtr(dat$Date, format = 'Q%q_%y') 

ggplot(dat, aes(x = Date)) + 
scale_x_yearqtr(format = 'Q%q_%y') + 
geom_line(aes(y = Estimate, group = Area, color = Area))+ 
geom_point(aes(y = Estimate, x = Date))+ 
geom_ribbon(aes(ymin = Lower, ymax = Upper), alpha = 0.2) 
+0

真棒 - 正是我需要的。幾乎看起來像一個錯誤,因爲它在參數之間不一致! – user1357015