Building two boxes in one position using R and ggplot2

I would like to build several boxes above / below each other and not next to each other in R using ggplot2 . Here is an example:

 library("ggplot2") set.seed(1) plot_data<-data.frame(loc=c(rep(1,200),rep(2,100)), value=c(rnorm(100,3,.5),rnorm(100,1,.25),2*runif(100)), class=c(rep("A",100),rep("B",100),rep("C",100))) ggplot(plot_data,aes(x=loc,y=value,group=class)) + geom_boxplot(fill=c("red","green","blue")) 

The result is the following graph:

example plot

As you can see, the blue square cell is centered around the loc (2.0) value, while the red and green cells are only half the width and are left and right of their common loc (1.0) value. I want both of them to be the same width as blue, and display them directly on top of each other.

How can i achieve this?

Please note that I am sure that the boxes will not overlap for the data that I am going to visualize, just as they are not for the data in this example.

+7
r ggplot2
source share
2 answers

Use position = "identity" :

 ggplot(plot_data,aes(x=loc,y=value,group=class)) + geom_boxplot(fill=c("red","green","blue"),position = "identity") 

enter image description here

By default, geom_boxplot uses position = "dodge" .

+9
source share

Main discussion: here

In short, you can use geom_boxplot(position=position_dodge(0)) . You can specify the distance between fields that change the value of "position_dodge".

+2
source share

All Articles