R中多标签数据的并排箱线图?

问题描述

我正在对 goodreads_score 和三个布尔自变量:fictionbest_sellerenglish间的关系进行探索性数据分析。

set.seed(1)
N <- 100
p <- rep(0.5,N)
id <- c(1,N)
fiction <- factor(rbinom(length(p),1,p))
best_seller <- factor(rbinom(length(p),p))
english <- factor(rbinom(length(p),p))
goodreads_score <- runif(100,5) 

df <- data.frame(id,fiction,best_seller,english,goodreads_score)

我知道如何为一个自变量绘制箱线图:

ggplot(df,aes(x=fiction,y=goodreads_score)) + 
  geom_Boxplot(colour = "#3366FF",outlier.shape = NA) + 
  geom_jitter(position=position_jitter(width=.1,height=0.1))

enter image description here

我想知道是否可以将所有三个标签放在一个图中(三个并排的组)?

解决方法

这可能满足您的需求:

df2 <- tidyr::gather(df,key = category,value = value,fiction:english,factor_key = TRUE )

ggplot(df2,aes(x=value,y=goodreads_score)) + 
  geom_boxplot(colour = "#3366FF",outlier.shape = NA) + 
  geom_jitter(position=position_jitter(width=.1,height=0.1)) +
  facet_wrap(~category,scale="free")

enter image description here

另一方面,如果您正在寻找基于指标值的所有类别的分组,您可以执行以下操作:

df2 <- tidyr::gather(df,factor_key = TRUE )

df2$cat_value <- paste0(df2$category,":",df2$value)
df2$cat_value <- factor(df2$cat_value,levels=c("fiction:0","best_seller:0","english:0","fiction:1","best_seller:1","english:1"))

ggplot(df2,aes(x=cat_value,height=0.1)) +
  geom_vline(xintercept = 3.5,color = "red",linetype = "dashed",size = 1.4)

enter image description here

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...