首页 > 解决方案 > 合并两个具有共同 x 轴的 coord_polar 图并添加 x 轴比例尺

问题描述

我希望创建一个图,其中一个圆形 coord_polar 图在另一个图内,共享 x 轴但具有不同的 y 轴。此外,我想在圆形图的内部添加一个比例尺,表示 x 轴的值。下面是一些测试数据:

library(dplyr)
library(ggplot2)

test_data <- data.frame(start = c(1, 200, 450, 600, 800),
                        end = c(150, 440, 570, 780, 1200),
                        gene_name = c("gene1", "gene2", "gene3", "gene4", "gene5"),
                        sample = 1,
                        gc = c(50.9, 49.8, 50.0, 51.0, 48.0)) %>%
  mutate(gene_length = end - start,
         pos = start + (gene_length/2)) %>%
  select(-gene_length)


p1 <- ggplot(test_data, aes(x = pos, y = gc)) +
  geom_col() +
  scale_y_continuous(limits = c(-60, 52)) +
  coord_polar()


p2 <- ggplot(test_data, aes(x = pos, fill = gene_name)) +
  geom_hline(aes(yintercept = sample + 0.4)) +
  geom_rect(aes(xmin = start, xmax = end, ymin = sample, ymax = sample + 0.8),
            color = "black",
            size = 0.01) +
  scale_y_continuous(limits = c(-10, 2)) +
  coord_polar()

p1

p1 看起来像这样

p2

p2 看起来像这样

我想要的是一个看起来有点像这样的情节(对不起,糟糕的画作): 在此处输入图像描述

主图外的黑色是由 p1 表示的条形图。我希望每个条的宽度在大小上与下面图中它们各自的元素相对应。我曾尝试将这些与cowplot 或aplot 等工具合并,但似乎都无法将它们放在一起。他们宁愿将它们放在彼此之上或之下。

标签: rggplot2

解决方案


为什么不将两个几何图形放在一个情节中,而不是尝试合并两个情节?请注意,为了强调不同之处gc

我已经在 ymin = 47 处开始了灰色区域,但如果你愿意,你可以将它们放回 0 并使内环处于负 y 值(因为它的 y 位置似乎是任意的)。

p1 <- ggplot(test_data, aes(x = pos, y = gc)) +
  geom_rect(aes(xmin = start, xmax = end, ymin = 47, ymax = gc)) +
  geom_hline(aes(yintercept = sample + 0.4)) +
  geom_rect(aes(fill = gene_name, xmin = start, xmax = end, 
                ymin = sample, ymax = sample + 1),
            color = "black",
            size = 0.01) +
  scale_y_continuous(limits = c(30, 52)) +
  scale_x_continuous(limits = c(0, 1250)) +
  coord_polar()

在此处输入图像描述


推荐阅读