【问题标题】:r -ggplot :Discrete y axis entries in ggplot?r -ggplot :ggplot中的离散y轴条目?
【发布时间】:2017-06-29 21:06:26
【问题描述】:

我有一个关于在 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 轴有四个离散条目,每个测试一个?

例如:

我还想按照匹配图块的数量对 x 轴进行排序,就像这样。

非常感谢您的宝贵时间。

【问题讨论】:

    标签: r ggplot2 graph


    【解决方案1】:

    我们将数据重新整形为长格式,计算患者的测试次数,并使用它来将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="")
    

    【讨论】:

    • 非常感谢,这绝对是我想要的,我也感谢您对流程的澄清。
    猜你喜欢
    • 1970-01-01
    • 2016-05-14
    • 1970-01-01
    • 2021-11-01
    • 1970-01-01
    • 2023-03-18
    • 2022-07-29
    • 2018-08-04
    • 2015-03-27
    相关资源
    最近更新 更多