8

ggplot2バー (男性、女性) とグループ (研究 1、研究 2...) の両方にドッジ グループと軸ラベルを使用して棒グラフを作成したいと思います。チャートをどのように表示したいかを次に示します。

ここに画像の説明を入力

そしていくつかのRコード。この場合、グループのみが軸上にラベル付けされます (グループ内の棒ではありません)。軸のバー ラベルは、基本的に凡例を置き換えます。

x      = runif(8)
gender = factor(c("male","female","male","female","male","female","male","female"))
group  = c(0,0,1,1,2,2,3,3)
df     = data.frame(x,gender,group)

ggplot(df,aes(x=group,y=x,fill=gender)) + 
    geom_bar(stat="identity",position="dodge") + 
    scale_x_continuous("",breaks=c(0:3),
        labels=c('G1','G2','G3','G4'))

ここに画像の説明を入力

4

1 に答える 1

8

このSOの質問に対する@Sandy Musprattの回答に触発されました。

最初に、凡例のないオブジェクト プロットを作成して保存し、x 軸のラベルを に、Femaleまたはに変更Malescale_x_continuous()ます。plot.margin=inを使用して、プロットの下に余分なスペースを追加しtheme()ます。

library(ggplot2)
library(gridExtra)
p<-ggplot(df,aes(x=group,y=x,fill=gender)) + 
  geom_bar(stat="identity",position="dodge") + 
  scale_x_continuous("",breaks=c(-0.25,0.25,0.75,1.25,1.75,2.25,2.75,3.25),
                     labels=rep(c("Female","Male"),times=4))+
  theme(legend.position="none")+
  theme(plot.margin = unit(c(1,2,3,1), "lines"))

関数を使用して、プロット設定 x および y 座標の下にラベルを追加します( annotation_custom()ytextGrob()の負の座標は、プロットの下にラベルを配置します)。Study 1Study 2

p1<-p+annotation_custom(grob=textGrob("Study 1"),
                          xmin=0,xmax=0,ymin=-.2,ymax=-0.2)+
      annotation_custom(grob=textGrob("Study 2"),
                          xmin=1,xmax=1,ymin=-.2,ymax=-0.2)+
      annotation_custom(grob=textGrob("Study 3"),
                          xmin=2,xmax=2,ymin=-.2,ymax=-0.2)+
      annotation_custom(grob=textGrob("Study 4"),
                          xmin=3,xmax=3,ymin=-.2,ymax=-0.2)

新しいラベルが確実にプロットされるようにするには、プロットを grobs オブジェクトに変換してから、クリッピングを無効にする必要があります。

gt <- ggplot_gtable(ggplot_build(p1))
gt$layout$clip[gt$layout$name=="panel"] <- "off"
grid.draw(gt)

ここに画像の説明を入力

于 2013-04-29T13:33:45.350 に答える