2017-08-10 118 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