首页 > 解决方案 > 如何在 R 中使用 ggplot2 创建这样的图形?

问题描述

在此处输入图像描述

我有一个包含许多零元素的矩阵。列名称标记在水平轴上。我想明确地将非零元素显示为每列垂直线的偏差。

那么应该如何使用 ggplot2 来构造一个像示例这样的图形呢?

可以生成如下示例数据:

set.seed(2018)
N <- 5
p <- 40
dat <- matrix(0.0, nrow=p, ncol=N)
dat[2:7,   1] <- 4*rnorm(6)
dat[4:12,  2] <- 2.6*rnorm(9)
dat[25:33, 3] <- 2.1*rnorm(9)
dat[19:26, 4] <- 3.3*rnorm(8)
dat[33:38, 5] <- 2.9*rnorm(6)
colnames(dat) <- letters[1:5]

print(dat)

标签: rggplot2

解决方案


facet_wrap这是使用and geom_colwith的另一个选项theme_minimal

library(tidyverse)
dat %>%
    as.data.frame() %>%
    rowid_to_column("row") %>%
    gather(key, value, -row) %>%
    ggplot(aes(x = row, y = value, fill = key)) +
    geom_col() +
    facet_wrap(~ key, ncol = ncol(dat)) +
    coord_flip() +
    theme_minimal()

在此处输入图像描述


为了进一步增加与您原始帖子中情节的美学相似性,我们可以

  1. 将刻面条移到底部,
  2. 旋转条形标签,
  3. 在匹配的颜色中添加“零线”,
  4. 删除fill图例,并且
  5. 摆脱 x & y 轴刻度/标签/标题。

library(tidyverse)
dat %>%
    as.data.frame() %>%
    rowid_to_column("row") %>%
    gather(key, value, -row) %>%
    ggplot(aes(x = row, y = value, fill = key)) +
    geom_col() +
    geom_hline(data = dat %>%
        as.data.frame() %>%
        gather(key, value) %>%
        count(key) %>%
        mutate(y = 0),
        aes(yintercept = y, colour = key), show.legend = F) +
    facet_wrap(~ key, ncol = ncol(dat), strip.position = "bottom") +
    coord_flip() +
    guides(fill = FALSE) +
    theme_minimal() +
    theme(
        strip.text.x = element_text(angle = 45),
        axis.title = element_blank(),
        axis.text = element_blank(),
        axis.ticks = element_blank())

在此处输入图像描述


推荐阅读