使用 ggplot2 条形之间的阴影区域

Pab*_*oAB 4 r ggplot2

我想使用 ggplot2 添加阴影区域,连接每个条形的类别,如图所示 在此输入图像描述

数据

library(ggplot2)
  
specie <- c(rep("sorgho" , 3) , rep("poacee" , 3) , rep("banana" , 3) , rep("triticum" , 3) )
condition <- rep(c("normal" , "stress" , "Nitrogen") , 4)
value <- abs(rnorm(12 , 0 , 15))
data <- data.frame(specie,condition,value)
  
ggplot(data, aes(fill=condition, y=value, x=specie)) + 
  geom_bar(position="fill", stat="identity", width = .5)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

All*_*ron 8

你所描述的更像是一个冲积地块,你应该检查一下ggalluvial

然而,在普通 ggplot 中可以使用大量数据操作和geom_area

library(tidyverse)

alluvia <- data %>%
  mutate(condition = factor(condition, c('Nitrogen', 'normal', 'stress'))) %>%
  group_by(specie) %>%
  arrange(specie, condition, by_group = TRUE) %>%
  mutate(y = value) %>%
  ungroup() %>%
  mutate(x = as.numeric(as.factor(specie))) %>%
  group_by(specie, condition) %>%
  summarise(x = c(x - 0.25, x, x + 0.25), y = y)

ggplot(alluvia %>% filter(x %% 1 == 0), aes(x, y, fill = condition)) +
  geom_area(data = alluvia, alpha = 0.4, position = 'fill') +
  geom_col(width = 0.5, color = 'gray50', position = 'fill') +
  scale_x_continuous(breaks = 1:4, labels = unique(alluvia$specie),
                     name = 'specie') +
  theme_minimal(base_size = 16) +
  scale_fill_brewer(palette = 'Set2') +
  theme(panel.grid.major.x = element_blank(),
        panel.grid.minor.x = element_blank())
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

对于 vanilla ggplot 中快速简单(但不那么漂亮)的等效项,您可以使用geom_area带有更细条形的 a :

ggplot(data, aes(fill=condition, y=value, x=specie)) + 
  geom_area(aes(group = condition), position = 'fill', alpha = 0.5) +
  geom_bar(position="fill", stat="identity", width = .25)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述