11

I would like to plot multiple boxplots above/below each other instead of 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"))

This results in the following plot:

example plot

As you can see, the blue boxplot is centered around its loc value (2.0), while the red and green ones have only half the width and are plotted to the left and right of their shared loc value (1.0). I want to make both of them the same width as the blue one and plot them directly above each other.

How can I achieve this?

Note that I am sure that the boxplots won't overlap for the data I am going to visualize, just as they don't for the given example data.

4

2 回答 2

14

使用position = "identity"

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

在此处输入图像描述

的默认值geom_boxplot是使用position = "dodge".

于 2013-07-10T16:16:10.333 回答
3

主要讨论是:这里

简而言之,可以使用geom_boxplot(position=position_dodge(0)). 可以指定不同'position_dodge'值的框之间的距离。

于 2015-10-06T07:54:57.607 回答