允许 ggplot2::geom_bar 中重复的 x 轴分类组

allowing duplicate x axis categorical groups in ggplot2::geom_bar

library(ggplot2)
library(viridis)
library(hrbrthemes)

# create a dataset
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, stringsAsFactors = FALSE)
data$condition[c(11, 12)] <- "other"

# Graph
ggplot(data, aes(fill = condition, y=value, x=condition)) + 
  geom_bar(position="dodge", stat="identity") +
  scale_fill_viridis(discrete = T, option = "E") +
  ggtitle("Studying 4 species..") +
  facet_grid(specie~., scales = "free", space = "free") +
  theme_ipsum() +
  theme(legend.position="none") +
  xlab("") +
  coord_flip() +
  theme(strip.text.x = element_text(angle = 0)) +
  theme_classic()

triticum 构面中有 2 行包含列 condition 的值 other

这样做是为了让该值显示 2 个单独的条。相反,只会出现 1 个栏。前者如何实现?

一个选项可能是为绘图定义一个辅助变量,例如 cond2,在 data 中使用离散名称,但使用 scale_x_discretecondition 标记,例如:

library(ggplot2)
library(viridis)
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, stringsAsFactors = FALSE)
data$condition[c(11, 12)] <- "other"
data$cond2 <- data$condition
data$cond2[c(11, 12)] <- make.unique(data$condition[c(11, 12)]) 

# Graph
ggplot(data, aes(fill = condition, y=value, x=cond2)) + 
    geom_bar(position="dodge", stat="identity") +
    scale_fill_viridis(discrete = T, option = "E") +
    scale_x_discrete(labels=setNames(data$condition, data$cond2)) +
    ggtitle("Studying 4 species..") +
    facet_grid(specie~., scales = "free", space = "free") +
    theme(legend.position="none") +
    xlab("") +
    coord_flip() +
    theme(strip.text.x = element_text(angle = 0)) +
    theme_classic()

reprex package (v2.0.0)

于 2021-05-31 创建