2017-08-10 9 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属性をどのように使用すればよいですか?

編集。今では良く見える

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') 

fausto.siegmundの答えは、私はラインの異なるタイプを使用してvar変数を分離させました。 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=interaction(variable,var)group=variableを変更し、これらの可能な組み合わせのためのユニークなラインをプロットするには:これは、プロットに要因があることを示しています。

完全なコードと結果のプロット。

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

関連する問題