Home > Net >  Why am I not getting divergent opposite bars?
Why am I not getting divergent opposite bars?

Time:11-10

I am trying to get divergent bar plots but somehow following different approaches I can't change the threshold to separate bars.

# RQ_avg is numeric continous variable, and gen is factor category (55 genes)

genes_plot2 <- genes_plot %>% dplyr::group_by(gen,RQ_avg) %>% nest()
genes_plot2 <- genes_plot2 %>% dplyr::mutate(Color = ifelse(RQ_avg >1, "green", "red"))

print(head(genes_plot2))
# A tibble: 6 × 4
# Groups:   gen, RQ_avg [6]
  gen   RQ_avg data                Color
  <chr>  <dbl> <list>              <chr>
1 ppara   1.35 <tibble [151 × 25]> green
2 ppard   1.40 <tibble [151 × 25]> green
3 pparg   1.29 <tibble [151 × 25]> green
4 nr1h3   1.30 <tibble [151 × 25]> green
5 nr1h2   1.39 <tibble [151 × 25]> green
6 rxra    1.40 <tibble [151 × 25]> green

ggplot(data = genes_plot2,
       aes(x = reorder(gen, RQ_avg), y = RQ_avg, 
           fill = Color)) 
  geom_bar(stat = "identity") 
  scale_fill_manual(values = c("green" = "green", "red" = "red"), guide = "none") 
  labs(x = "Gene", y = "Fold change value",
       title = "Gene expression",
       subtitles = "Relative quantification") 
  theme_minimal() 
  guides(fill = F)

enter image description here

What I really want is sthg like this, with the number I specifically detail as threshold breakpoint

enter image description here

Thank you so much!

CodePudding user response:

You'll want your bar height to be distance from your specified value, so create a new y value by subtraction (then test for direction to choose fill colour):

library(tidyverse)

df <- tibble(gen = LETTERS,
       RQ_ave = runif(26, 1, 10))

df |> 
  mutate(val = RQ_ave - 5,
         direction = val > 0) |> 
  ggplot(aes(fct_reorder(gen, val), val, fill = direction))  
  geom_bar(stat = "identity")  
  coord_flip()  
  theme(legend.position = "none")

  • Related