Reputation: 37
I will use the following data generated by someone else to explain what I need. Please run the codes and you will see that you have this plot:
What I need is to have the same plot and at the left side (besides enzymes 1 to 4) have enzymes category (enzymes 1 and 3 as category 1 and enzymes 2 and 4 as category 2). Would you please help me on that?
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"))
Upvotes: 1
Views: 79
Reputation: 16178
One possible solution is to facetted your graph using facet_grid
in function of "Category" as follow:
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())
Does it answer your question ?
Upvotes: 1