2017-08-10 174 views
0

我想用這個數據幀,使一個情節:R + ggplot:繪製許多變數

val = c(27.9, 35.5, 28.2, 20.7, 9.3, 7.3, 9.2, 8.8, 14.2, 13.7, 12.4, 41.3, 31.8, 
       44.0, 28.0, 17.5, 6.1, 6.9, 5.7, 9.8, 8.8, 21.9, 13.7, 26.2, 22.8,  
       21.6, 15.2, 15.2, 3.4, 2.9, 4.2, 3.3, 8.1, 9.2, 8.5, 25.8, 34.1, 
       36.6, 28.1, 10.4, 3.9, 15.8, 24.9, 19.5, 21.8, 22.2, 19.1, 22.0) 
df = data.frame(variable=rep(c('E1', 'E2'), 
       each=12,2), 
       value=val, 
       mes= rep(month.abb,4), 
       var=rep(c('orig', 'trat'), each=24)) 
str(df) 
    'data.frame': 48 obs. of 4 variables: 
    $ variable: Factor w/ 2 levels "E1","E2": 1 1 1 1 1 1 1 1 1 1 ... 
    $ value : num 27.9 35.5 28.2 20.7 9.3 7.3 9.2 8.8 14.2 13.7 ... 
    $ mes  : Factor w/ 12 levels "Apr","Aug","Dec",..: 5 4 8 1 9 7 6 2 12 11 ... 
    $ var  : Factor w/ 2 levels "orig","trat": 1 1 1 1 1 1 1 1 1 

探索,我做了這個情節:

ggplot(df, 
     aes(mes, value, group=variable, color=variable, shape=var)) + 
     scale_x_discrete(limits = month.abb) + 
     geom_point() + geom_line() + 
     theme(legend.position = 'bottom') 

ggplot輸出是不是我所期待但是當通過ggplotly函數時,它就成了我的意圖。除了

,如果我通過了選項:爲了使用不同的線路類型分隔兩VAR值...aes(mes, value, group=variable, color=variable, shape=var, linetype=var)...我得到的錯誤:錯誤:geom_path:如果您使用的是點線或虛線,顏色,大小和線型必須不斷超過線路

那麼,有什麼用ggplot圖形發生什麼呢?我應該如何使用ggplot函數內linetype屬性?

編輯。 fausto.siegmund的回答讓我使用不同類型的線var變量分離:

ggplot(df, 
     aes(mes, value, group=interaction(variable,var), color=variable, linetype=var)) + 
    scale_x_discrete(limits = month.abb) + 
    geom_point() + geom_line() + 
    theme(legend.position = 'bottom') 

現在它看起來更好。一瞥可以同時欣賞var因素。

謝謝fausto.siegmund!

+0

嘗試'組=互動(變量VAR)'的'ggplot(...)'您發佈。這是否會產生你想要的結果? –

+0

它工作。把它當作答案來標記它。 – noriega

回答

1

要查看需要繪製的varvariable中的因子水平組合,請運行levels(interaction(df$variable,df$var))。這表明,對情節的因素有:

"E1.orig" "E2.orig" "E1.trat" "E2.trat" 

要繪製獨特的線條,這些可能的組合,修改group=variablegroup=interaction(variable,var)

的完整代碼和產生的情節。

val = c(27.9, 35.5, 28.2, 20.7, 9.3, 7.3, 9.2, 8.8, 14.2, 13.7, 12.4, 41.3, 31.8, 
       44.0, 28.0, 17.5, 6.1, 6.9, 5.7, 9.8, 8.8, 21.9, 13.7, 26.2, 22.8,  
       21.6, 15.2, 15.2, 3.4, 2.9, 4.2, 3.3, 8.1, 9.2, 8.5, 25.8, 34.1, 
       36.6, 28.1, 10.4, 3.9, 15.8, 24.9, 19.5, 21.8, 22.2, 19.1, 22.0) 
df = data.frame(variable=rep(c('E1', 'E2'), 
       each=12,2), 
       value=val, 
       mes= rep(month.abb,4), 
       var=rep(c('orig', 'trat'), each=24)) 

ggplot(df, 
     aes(mes, value, group=interaction(variable,var), color=variable, shape=var)) + 
    scale_x_discrete(limits = month.abb) + 
    geom_point() + geom_line() + 
    theme(legend.position = 'bottom') 

enter image description here