如何使用geom_bar在ggplot2中制作连接的条形图? [英] How to use geom_bar for making connected bar plot in ggplot2?
问题描述
我正在尝试使用geom_bar获取条形图
I'm trying to use geom_bar for getting a bar plot
用线连接.如何绘制样本之间的连接线?
connected with lines. How to draw connecting lines between samples?
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进行了尝试,但看起来很奇怪
I tried it by using both geom_bar and geom_line, but it looks weird
.
似乎连接的线从A样本的中心开始到B样本的中心.
It looks like connected line starts from the center of A sample to the center of B sample.
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样本的条的左边缘开始.
I want to get a better plot like connected line starts from the right edge on the bar of A sample to the left edge on the bar of B sample.
我该怎么做?
推荐答案
我不知道执行此操作的内置方法,但是如果您知道,可以使用 geom_segment
完成相同的操作酒吧在哪里.
I'm not aware of a built-in way to do this, but you can accomplish the same using geom_segment
if you know where the bars are.
首先提供一些虚假数据:
First some fake data:
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)
)
为了简化连接,我将数据扩展为宽格式,以便每条连接线都获得一行,其中一列与第一个Sample相关,另一列与第二个Sample相关:
To make the connections simpler, I spread the data to wide format so each connecting line gets a row, with one column related to the first Sample and the other for the 2nd Sample:
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
这篇关于如何使用geom_bar在ggplot2中制作连接的条形图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!