r -ggplot:ggplot中的离散y轴条目?

时间:2017-06-29 21:06:26

标签: r ggplot2 graph

我有一个关于在ggplot或者r中绘图的问题。

如果我的数据框看起来像这样:

df <- data_frame(Patients = c(1:10),
                 test1 = sample(c(0,1), 10, replace = TRUE),
                 test2 = sample(c(0,1), 10, replace = TRUE),
                 test3 = sample(c(0,1), 10, replace = TRUE),
                 test4 = sample(c(0,1), 10, replace = TRUE))

然后输出看起来像这样。

# A tibble: 10 x 5
   Patients test1 test2 test3 test4
      <int> <dbl> <dbl> <dbl> <dbl>
 1        1     0     1     1     0
 2        2     1     0     1     1
 3        3     1     0     0     1
 4        4     1     1     0     1
 5        5     1     0     1     1
 6        6     1     0     0     1
 7        7     1     1     1     0
 8        8     1     0     0     1
 9        9     1     0     1     1
10       10     0     1     0     1

如何制作患者在x轴上作为离散条目的图表,y轴有四个离散条目,每个测试一个?

例如: enter image description here

我还想按照匹配的瓷砖数量来订购x轴。

enter image description here

非常感谢你的时间。

1 个答案:

答案 0 :(得分:0)

我们将数据重新整形为长格式,计算患者的测试次数,并使用该数据将Patients转换为具有所需排序的因子。

library(tidyverse)
library(forcats)
library(stringr)
theme_set(theme_minimal())

set.seed(2)
df <- data_frame(Patients = c(1:10),
                 test1 = sample(c(0,1), 10, replace = TRUE),
                 test2 = sample(c(0,1), 10, replace = TRUE),
                 test3 = sample(c(0,1), 10, replace = TRUE),
                 test4 = sample(c(0,1), 10, replace = TRUE))

ggplot(gather(df, Test, value, -Patients) %>%
         group_by(Patients) %>%
         mutate(Test = str_to_title(gsub("(.*)([0-9])", "\\1 \\2", Test)),
                numTests = sum(value)) %>%
         ungroup %>%
         arrange(numTests, Patients) %>%
         mutate(Patients = fct_inorder(factor(Patients))), 
       aes(Patients, Test, fill=factor(value))) +
  geom_tile(colour="grey60", lwd=0.8, show.legend=FALSE) +
  scale_fill_manual(values=c("white","black")) +
  labs(x="Patient", y="")

enter image description here

相关问题