Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adjust boxplot bar position with ggplot2 package

Tags:

r

ggplot2

I am trying to create a plot that overlaps two previously generated plots. The result was very close to what I want however, I was not able to adjust the interval between each bar. Below are codes i was using to generate boxplots,

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

and the result are shown as below,enter image description here

I am wondering how to make the vertical lines of boxplots on the upper level can overlap with those beneath them while i can keep the upper bars narrower (that is, how can I add an interval between consecutive bars, so that they are not immediately next to each other?)

* In addition, I would also need to shift all boxplot horizontally on the plot. Is there a way I can adjust boxplots' x-axis position without changing the x-axis? *

Thank you very much for your help!

like image 557
Samuel Song Avatar asked Aug 16 '13 01:08

Samuel Song


1 Answers

Answered in comments:

geom_boxplot(..., position = position_dodge(width = 0.75))
like image 67
Roman Avatar answered Oct 30 '22 02:10

Roman