2016-11-17 5 views
2

私は以下のサンプルデータに似たデータを持っていますが、私はGenotype列に沿って測定カラムのヒストグラムを描こうとしています。最終的に、私はバーの色をGenotypeとConditionの列で条件付きにしたいと思います。 facet_wrap()を使用したggplot2ヒストグラムの等しいバー幅

library(ggplot2) 
library(dplyr) 

set.seed(123) 
DF <- data.frame(Genotype = rep(c("A", "B"), 500), 
       Condition = sample(c("E", "L"), 1000, replace = T), 
       Measurment = round(rnorm(500,10,3), 0)) 

DF <- anti_join(DF, filter(DF, Genotype == "B" & Condition != "E"))' 

head(DF) 

    Genotype Condition Measurment 
1  A   L   18 
2  A   L   2 
3  B   E   18 
4  B   E   18 
5  B   E   16 
6  B   E   16 

は今、私はそれが最も簡単に作成するために考えられたバーの色を指定する:

極めて重要な遺伝子型Bの個人がL.

条件で測定されなかったこれは、データがどのように見えるかですGenotype Bの全ての個体が条件1の下で測定される場合、条件Bのすべての個体が1色であり、遺伝子型Aの個体が条件2で測定される場合には2番目の色であるような新しい6桁の列。

DF <- DF %>% mutate(colr = ifelse(Genotype == "B", "#409ccd", 
          ifelse(Condition == "E", "#43cd80", "#ffc0cb"))) 
このようなようにそれを

ggplot(data=DF, aes(Measurment, fill = Condition)) + 
    geom_histogram(aes(y=..count.., fill = colr), position='dodge', binwidth = 1) + 
    facet_wrap(~Genotype, nrow=2) + 
    scale_fill_manual(values = c("#409ccd","#ffc0cb","#43cd80")) + 
    theme(legend.position="none") 

と::私はその後、ヒストグラムを描くことができます3210

はそうのような遺伝子型の列にファセット

graph

をしかしあなたはジェノタイプBの列を見ることができるように遺伝子型Aの2倍の大きさです。どのように遺伝子型Bを遺伝子型Aと同じサイズに縮小できますか?

遺伝子型Bが条件Lのエントリを持つ私のデータにダミーエントリを追加することを考えましたが、ビニング機能はこれを誤解を招く測定値としてカウントします。私もgeom_bar()を使ってこのバージョンを持っていますが、同様の問題が発生します。 ggplotにはこれを行う方法が必要です。

助けてください。

答えて

2

多分このような何か?

ggplot(data=DF, aes(Measurment, fill = Condition)) + 
    geom_histogram(data=subset(DF, Genotype!="B"),aes(y=..count.., fill = colr), position='dodge', binwidth = 1) + 
    geom_histogram(data=subset(DF, Genotype=="B"),aes(x = Measurment, y=..count.., fill = colr), position=position_nudge(x=0.25), binwidth = 0.5) + 
    facet_wrap(~Genotype, nrow=2) + 
    scale_fill_identity() + 
    theme(legend.position="none") 

enter image description here

0

次のようなものが欲しいですか?私はあなたのバーの幅を意味する列のサイズを前提としていました。

library(grid) 
library(gridExtra) 
p1 <- ggplot(data=DF[DF$Genotype=='A',], aes(Measurment, fill = Condition)) + 
    geom_histogram(aes(y=..count.., fill = colr), position='dodge', binwidth = 1) + 
    scale_fill_manual(values = c("#43cd80","#ffc0cb")) + 
    theme(legend.position="none") 
p2 <- ggplot(data=DF[DF$Genotype=='B',], aes(Measurment, fill = Condition)) + 
    geom_histogram(aes(y=..count.., fill = colr), binwidth = 0.5, boundary = 1) + 
    scale_fill_manual(values = c("#409ccd")) + 
    theme(legend.position="none") 
grid.arrange(p1, p2) 

enter image description here

+0

閉じるが、私は青いバーが直接、ピンクのものを下回るようにしたいです。私は、facet_wrap()ソリューションを期待していました。 –

関連する問題