简体   繁体   English

使用R和ggplot2在一个x位置绘制两个箱线图

[英]Plotting two boxplots at one x position using R and ggplot2

I would like to plot multiple boxplots above/below each other instead of next to each other in R using ggplot2 . 我想在ggplot2中使用ggplot2R之上/之下绘制多个箱图,而不是在Rggplot2 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: 这导致以下情节:

示例情节

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). 如您所见,蓝色框图以其loc值(2.0)为中心,而红色和绿色仅具有宽度的一半,并绘制在其共享的loc值(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. 请注意,我确信箱形图对于我要显示的数据不会重叠,就像它们不适用于给定的示例数据一样。

Use position = "identity" : 使用position = "identity"

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

在此输入图像描述

The default for geom_boxplot is to use position = "dodge" . geom_boxplot的默认geom_boxplot是使用position = "dodge"

The main discussion is: here 主要讨论是: 这里

Briefly, one can use geom_boxplot(position=position_dodge(0)) . 简而言之,可以使用geom_boxplot(position=position_dodge(0)) One can specify the distance between the boxes varying 'position_dodge' value. 可以指定改变'position_dodge'值的方框之间的距离。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM