web-dev-qa-db-ja.com

ggplot:連続xの各グループに複数のy変数の箱ひげ図を配置する

連続x変数のグループに対して複数の変数の箱ひげ図を作成したいと思います。ボックスプロットは、xの各グループごとに並べて配置する必要があります。

データは次のようになります。

require (ggplot2)
require (plyr)
library(reshape2)

set.seed(1234)
x   <- rnorm(100)
y.1 <- rnorm(100)
y.2 <- rnorm(100)
y.3 <- rnorm(100)
y.4 <- rnorm(100)

df <- as.data.frame(cbind(x,y.1,y.2,y.3,y.4))

それを溶かしました

dfmelt <- melt(df, measure.vars=2:5)    

このソリューションに示されているfacet_wrap( ggplot(facets)の因子による複数のプロット )は、個々のプロットの各変数を提供しますが、各変数のボックスプロットを隣り合わせにしたいと思います1つの図のxの各ビンに対して。

ggplot(dfmelt, aes(value, x, group = round_any(x, 0.5), fill=variable))+
geom_boxplot() + 
geom_jitter() + 
facet_wrap(~variable)

fig1

これは、y変数を隣り合わせて表示しますが、xをビン化しません。

ggplot(dfmelt) +
geom_boxplot(aes(x=x,y=value,fill=variable))+
facet_grid(~variable)

fig2

ここで、xのビンごとにこのようなプロットを作成したいと思います。

何を変更または追加する必要がありますか?

15
sina

探しているものが正確にわかりません。これは近いですか?

enter image description here

_library(ggplot2)
library(plyr)
ggplot(dfmelt, aes(x=factor(round_any(x,0.5)), y=value,fill=variable))+
  geom_boxplot()+
  facet_grid(.~variable)+
  labs(x="X (binned)")+
  theme(axis.text.x=element_text(angle=-90, vjust=0.4,hjust=1))
_

[〜#〜] edit [〜#〜](OPのコメントへの応答)

facet_grid(...)呼び出しを取り出すだけで、各ビンにYを並べることができますが、お勧めしません。

_ggplot(dfmelt, aes(x=factor(round_any(x,0.5)), y=value, fill=variable))+
  geom_boxplot()+
  labs(x="X (binned)")+
  theme(axis.text.x=element_text(angle=-90, vjust=0.4,hjust=1))
_

この方法で行う必要がある場合は、ファセットを使用するとさらに明確になります。

_dfmelt$bin <- factor(round_any(dfmelt$x,0.5))
ggplot(dfmelt, aes(x=bin, y=value, fill=variable))+
  geom_boxplot()+
  facet_grid(.~bin, scales="free")+
  labs(x="X (binned)")+
  theme(axis.text.x=element_blank())
_

bin列がdfmeltに追加されていることに注意してください。これは、factor(round_any(x,0.5))式でfacet_grid(...)を使用しても機能しないためです。

30
jlhoward