使用ggplot2包调整boxplot bar位置

时间:2013-08-16 01:34:07

标签: r ggplot2

我正在尝试创建一个与之前生成的两个图重叠的图。结果非常接近我想要的,但是我无法调整每个条之间的间隔。以下是我用于生成箱线图的代码,

a <- ggplot(aes(y = SCORE, x = DATE, fill = CATEGORY), data = data_R1000) +          geom_boxplot() + ylim(20,100) + labs(title = "Russell 1000") + theme(legend.position="bottom") + scale_fill_hue(c=150, l=70)

b <- ggplot(aes(y = SCORE, x = DATE, fill = CATEGORY), data = data_R1000) + geom_boxplot(width=0.8) + ylim(20,100) + labs(title = "US_MARKETOR") + theme(legend.position="bottom") + theme(panel.background = element_rect(fill = "transparent",colour = NA)) + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()) + scale_fill_hue(c=50, l=85)

# extract gtable
g1 <- ggplot_gtable(ggplot_build(a))
g2 <- ggplot_gtable(ggplot_build(b))

# overlap the panel of 2nd plot on that of 1st plot
pp <- c(subset(g1$layout, name == "panel", se = t:r))
g <- gtable_add_grob(g1, g2$grobs[[which(g2$layout$name == "panel")]], pp$t, pp$l, pp$b, pp$l)

## what I dd is to plot a new viewports.
vp=viewport(x=0.5,y=0.5,height=1,width=1)
pushViewport(vp)
grid.draw(g)
upViewport()

,结果显示如下,enter image description here

我想知道如何使上层的箱线图的垂直线与它们下面的那些重叠,而我可以保持上栏更窄(也就是说,如何在连续的栏之间添加间隔,以便它们是不是紧挨着彼此?)

*此外,我还需要在绘图上水平移动所有箱线图。有没有办法在不改变x轴的情况下调整箱形图的x轴位置? *

非常感谢你的帮助!

1 个答案:

答案 0 :(得分:0)

已在评论中答复

geom_boxplot(..., position = position_dodge(width = 0.75))