下面我用别人生成的数据来解释一下我所需要的东西。请运行代码,你会看到你有这个图。
我需要的是同样的图,在左边(除了酶1到4)有酶的类别(酶1和3为1类,酶2和4为2类)。请您帮我解决这个问题。
library(tidyverse)
data_wide <- tibble(ethnicity = c("ethnicity1", "ethnicity2"),
enzyme1 = c(-1, -2),
enzyme2 = c(1, 1),
enzyme3 = c(1, 2),
enzyme4 = c(-1, 1))
data_long <- data_wide %>%
pivot_longer(starts_with("enzyme"), "enzyme")
data_long$Category= c("Category1", "Category2", "Category1", "Category2", "Category1", "Category2", "Category1", "Category2")
data_long1=subset(data_long, ethnicity=="ethnicity1")
data_long1[["sign"]] = ifelse(data_long1[["value"]] >= 0, "positive", "negative")
library(ggplot2)
ggplot()+
geom_col(data = data_long1, aes(x = enzyme,
y = value,fill = sign))+
geom_hline(aes(yintercept = 0))+
coord_flip()+
theme_linedraw()+ geom_bar() +
scale_fill_manual(values = c("positive" = "green", "negative" = "red"))
一个可能的解决方案是将你的图形分面,使用的是 facet_grid
功能中的 "类别 "如下。
library(ggplot2)
ggplot(data = data_long1, aes(x = reorder(enzyme, desc(enzyme)),
y = value,fill = sign))+
geom_col()+
geom_hline(aes(yintercept = 0))+
coord_flip(clip = "off")+
scale_fill_manual(values = c("positive" = "green", "negative" = "red"))+
facet_grid(Category~., scales = "free_y", switch = "y", space = "free_y")+
theme(strip.text.y.left = element_text(angle = 0, face = "bold", vjust = 1),
strip.background = element_blank(),
strip.placement = "outside",
axis.title.y = element_blank())
它能回答你的问题吗?