使用R和ggplot2在一个x位置绘制两个箱形图 [英] Plotting two boxplots at one x position using R and ggplot2
问题描述
我想在 R
中使用 ggplot2
来绘制多个盒形图,而不是彼此相邻的多个盒形图>。
下面是一个例子:
$ b
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)) )
结果如下:
<正如你所看到的那样,你可以看到,如果你已经看到了这个图像,蓝色boxplot以它的 loc
值(2.0)为中心,而红色和绿色的只有一半的宽度,并绘制在它们共享的 loc
值(1.0)。
我想让它们的宽度与蓝色的宽度相同,并将它们直接叠加在一起。
我该如何实现这一目标?
>请注意,我确信箱线图对于我将要显示的数据不会重叠,就像它们不适用于给定示例数据一样。
position =identity
: ggplot(plot_data,aes(x = loc,y = value,group = class))+
geom_boxplot(fill = c (红色,绿色,蓝色),位置=身份)
< img src =https://i.stack.imgur.com/CeF7L.pngalt =
默认值为 geom_boxplot
是使用 position =dodge
。
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:
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.
Use 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"
.
这篇关于使用R和ggplot2在一个x位置绘制两个箱形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!