2017-08-25 107 views
1

我有一个结构类似这样的数据:GGPLOT2 geom_rect积四分位数堆放着数据点和离散x轴

msr_type <- c('Clinic','Hospital','Lab','Office') 
result <- c(10.5, 21.9, 30.5, 14.5) 
sec_q <- c(9.5, 15.2, 25, 9) 
third_q <- c(11, 17, 34, 20) 
four_q <- c(17, 25, 29, 25) 
df_check <- data.frame(msr_type, result, sec_q, third_q, four_q) 

这是很容易绘制结果作为点:

ggplot() + geom_point(data=df_check, aes(x=msr_type, y=result), colour="blue") 

enter image description here

但是有没有一种方法可以使用geom_rect根据msr_type绘制四分位数,因为它是一个堆叠在一起的离散变量?

+0

什么是'df_practice2'?您的示例数据仅创建'df_check',并且使用该数据源生成的ggplot看起来不像图片。 –

+0

这是一个错字,正如我的问题所述,难点不是创建一个点 - 它是背景中堆积的四分位矩形/条。要用严格的词汇来解释我需要的东西太困难了,所以我做了一个模拟来表明总体思路。 – PinkyL

回答

1

以下是两种可能的方法,具体取决于您的需要。无论如何,我认为geom_col会更容易。 (这是可能的使用geom_rect当你的x轴数据是离散的,但它不是最直接的。Example)(我切换Q3 & Q4值实验室作为Q3的价值

的样本数据是较大的,这并没有使义):

msr_type <- c('Clinic','Hospital','Lab','Office') 
result <- c(10.5, 21.9, 30.5, 14.5) 
sec_q <- c(9.5, 15.2, 25, 9) 
third_q <- c(11, 17, 29, 20) 
four_q <- c(17, 25, 34, 25) 
df_check <- data.frame(msr_type, result, sec_q, third_q, four_q) 

方法1(保持原始数据集的宽格式):

ggplot(df_check, 
     aes(x = msr_type)) + 
    geom_col(aes(y = four_q), fill = "slategray3") + 
    geom_col(aes(y = third_q), fill = "slategray2") + 
    geom_col(aes(y = sec_q), fill = "slategray1") + 
    geom_point(aes(y = result)) + 
    xlab("") + ylab("") 

由于Q2 < = Q3 < = Q4,您可以简单地为每个四分位数组重新创建一组条形码组。但是,如果你需要为Q2/Q3/Q4一个传奇,它不是那么简单......

Approach 1

方法2(数据集转换为长格式,使所有的四分位值是相同的变量):

df_check2 <- df_check %>% 
    tidyr::gather(quartile, quartile.value, -msr_type, -result) %>% 
    mutate(quartile = factor(quartile, levels = c("sec_q", "third_q", "four_q"))) 

ggplot(df_check2, 
     aes(x = msr_type)) + 
    geom_col(aes(y = quartile.value, fill = quartile), 
      position = position_dodge(0), width = 2.5) + 
    geom_point(aes(y = result)) + 
    scale_fill_manual(values = c("slategray1", "slategray2", "slategray3")) + 
    xlab("") + ylab("") 

默认情况下使用此方法创建图例。如果你有其他四分位数/十分位数/百分位数/等等来绘制,它也更加灵活。

Approach 2

+0

荣誉。我甚至不知道有geom_col,这太棒了! – PinkyL