【问题标题】:How to use geom_bar for making connected bar plot in ggplot2?如何使用 geom_bar 在 ggplot2 中制作连接条形图?
【发布时间】:2019-07-30 01:37:50
【问题描述】:

我正在尝试使用 geom_bar 来获取条形图

用线连接。 如何绘制样本之间的连接线?

ggplot()+
  geom_bar(data = data_bar,
           aes(x = Sample, y =Percentage, fill = Taxon),
           colour = 'white', width =0.3, stat="identity")+
  guides(fill= guide_legend(ncol = 1))

我用 geom_bar 和 geom_line 都试过了,但是看起来很奇怪

.

看起来连接线从A样本的中心开始到B样本的中心。

ggplot()+
  geom_bar(data = data_bar,
           aes(x = Sample, y =Percentage, fill = Taxon),
           colour = 'white', width =0.3, stat="identity")+
  geom_line(data = rev(data),
            aes(x = Sample, y =Percentage, group = Taxon, color = Taxon),
            size = 0.3, stat = 'identity')+
  guides(fill= guide_legend(ncol = 1))

我想得到一个更好的图,比如连接线从 A 样本条的右边缘开始到 B 样本条的左边缘。

我该怎么做?

【问题讨论】:

标签: r ggplot2


【解决方案1】:

我不知道执行此操作的内置方法,但如果您知道栏在哪里,您可以使用 geom_segment 完成同样的操作。

首先是一些假数据:

set.seed(0)
data_bar <- data.frame(
  stringsAsFactors = F,
  Sample = rep(c("A", "B"), each = 10),
  Percentage = runif(20),
  Taxon = rep(1:10, by = 2)
)

为了使连接更简单,我将数据展开为宽格式,因此每条连接线都有一行,其中一列与第一个样本相关,另一列与第二个样本相关:

library(tidyverse)
ggplot() +
  geom_bar(data = data_bar,
           aes(x = Sample, y =Percentage, fill = Taxon),
           colour = 'white', width = 0.3, stat="identity") +
  geom_segment(data = tidyr::spread(data_bar, Sample, Percentage)
               colour = "white",
               aes(x = 1 + 0.3/2,
                   xend = 2 - 0.3/2,
                   y = cumsum(A),
                   yend = cumsum(B))) +
  theme(panel.background = element_rect(fill = "black"), # to make connecting points          
        panel.grid = element_blank())                    # show up more clearly

【讨论】:

  • 嗨@jon-spring 关于如何将其扩展到三个或更多类别(A、B、C)的任何提示?谢谢
  • (这是作为基础 R 替代方案:gist.github.com/JEFworks/…