箱图中的单独子组

问题描述

我已经使用箱形图可视化了一些数据。每个变量都属于一个子组,我想在箱图中对这些子组进行分隔/指示。在每个“变量组”之间创建一个小间隙,或者使用fill = type在属于 的不同变量上以某种方式指示。下面,我生成了一些可以用作示例数据的数据。

require(tidyverse)

set.seed(1234)
value <- sample(20:80,1000,replace = T)
group <- sample(c("A1","A2","B1","B2","C1","C2"),TRUE)

df <- as.data.frame(cbind(value,group))

df <- df %>%
  mutate(value = as.numeric(value),type = ifelse(grepl("*2",group),"Group 2","Group1"),) 

ggplot(df,aes(x=value,y =group))+
  geom_Boxplot() +
  xlim(0,100)

这给出了以下箱线图:

enter image description here

我尝试通过添加facet_wrap(~type,dir="v")来对图进行分组,生成以下图:

enter image description here

但是,我不知道如何删除空变量(例如,在第2组中:A1,B2,C3)。

有人知道如何(不使用facet_wrap()来(不使用fill = type)在箱形图中指示变量子组而不使用#include <iostream> using namespace std; void func(int&& a){ std::cout << a << " from rvalue" << std::endl; } int main(){ int&& ref = 6; //func(ref); // error func(6); // holds good return 0; } // error -> cannot bind rvalue reference of type 'int&&' to lvalue of type 'int' 吗?

解决方法

您可以使用scales = "free"删除未使用的因子水平:

library(dplyr)
library(ggplot2)

set.seed(1234)
value <- sample(20:80,1000,replace = T)
group <- sample(c("A1","A2","B1","B2","C1","C2"),TRUE)

df <- as.data.frame(cbind(value,group))

df <- df %>%
  mutate(value = as.numeric(value),type = ifelse(grepl("*2",group),"Group 2","Group1"),) 

ggplot(df,aes(x=value,y =group))+
  geom_boxplot() +
  xlim(0,100) +
  facet_wrap(~type,dir="v",scales = "free")

reprex package(v0.3.0)于2020-09-11创建