将箱图与单个值进行比较

时间:2017-06-20 08:21:39

标签: r ggplot2 boxplot facet

我想将几个变量(此处为X1X2)的分布与单个值(此处为bm)进行比较。问题是这些变量太多(大约十几个)使用单个箱图。 enter image description here

另外,使用一个图表的级别太不同了。我需要使用方面来使事情更有条理:enter image description here

然而,对于此图,我的基准类别(bm)(X1X2中的单个值)未出现在X1中,似乎有几个X2中的值。我希望它只是这条绿线,它在第一个情节中。任何想法为什么会改变?有什么好的解决方法吗?我尝试了facet_wrap / facet_grid的选项,但没有提供正确的结果。

我还尝试将条形图与bm和三个空类别与箱形图组合。但首先它看起来很糟糕,其次它同样搞砸了。基本上任何工作都会有所帮助。

在代码下方创建此处显示的最小示例:

# Creating some sample data & loading libraries
library(ggplot2)
library(RColorBrewer)
set.seed(10111)
x=matrix(rnorm(40),20,2)
y=rep(c(-1,1),c(10,10))
x[y==1,]=x[y==1,]+1
x[,2]=x[,2]+20
df=data.frame(x,y)

# creating a benchmark point
benchmark=data.frame(y=rep("bm",2),key=c("X1","X2"),value=c(-0.216936,20.526312))
# melting the data frame, rbinding it with the benchmark
test_dat=rbind(tidyr::gather(df,key,value,-y),benchmark)

# Creating a plot
p_box <- ggplot(data = test_dat, aes(x=key, y=value,color=as.factor(test_dat$y))) +
    geom_boxplot() +  scale_color_manual(name="Cluster",values=brewer.pal(8,"Set1"))

# The first line delivers the first plot, the second line the second plot
p_box
p_box + facet_wrap(~key,scales = "free",drop = FALSE) + theme(legend.position = "bottom")

1 个答案:

答案 0 :(得分:1)

问题只在于test_dat$y在颜色aes中的使用。永远不要在$中使用aes,ggplot会搞砸。

无论如何,如果您使用geom_hline作为基准,而不是在单一值框图中进行黑客攻击,我认为您的情节会有所改善:

library(ggplot2)
library(RColorBrewer)

ggplot(tidyr::gather(df,key,value,-y)) +
    geom_boxplot(aes(x=key, y=value, color=as.factor(y))) +
    geom_hline(data = benchmark, aes(yintercept = value), color = '#4DAF4A', size = 1) +
    scale_color_manual(name="Cluster",values=brewer.pal(8,"Set1")) +
    facet_wrap(~key,scales = "free",drop = FALSE) + 
    theme(legend.position = "bottom")

相关问题