Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2 horizontal barplot with gradient color fill

I am trying to create horizontal bar plot and would like to fill the individual bar as per their log fold values, white for lowest value and darkest for highest value. However, I am not able to do it. Here is my work, can somebody help me fix it?

df <- data.frame(LogFold = c(14.20, 14.00, 8.13, 5.3, 3.8, 4.9, 1.3, 13.3, 14.7, 12.2),
              Tissue = c("liver", "adrenal", "kidney", "heart", "limb", "adipose", "brown", "hypothalamus", "arcuate", "lung"))
df1<-df%>%
arrange(desc(LogFold))

ggplot(data=df1, aes(x=Tissue, y=LogFold, fill = Tissue)) +
geom_bar(stat="identity")+
scale_colour_gradient2()+
coord_flip()+
ylim(0, 15)+
scale_x_discrete(limits = df1$Tissue)+
theme_classic()

enter image description here

Thank You in advance!

like image 908
Umesh Avatar asked Mar 07 '23 15:03

Umesh


1 Answers

Here's what you need to think about:

  • sorting the data frame values makes no difference to ggplot
  • in your code you are mapping fill color to Tissue, not to LogFold
  • the newer geom_col is less typing than geom_bar(stat = ...)
  • the limits to your scale are unnecessary as you specify all values for Tissue
  • if you want to fill with a gradient use scale_fill_gradient2()
  • fill = white will not be visible on the white background of theme_classic

So you could try something like this:

library(tidyverse)
df1 %>% 
  ggplot(aes(reorder(Tissue, LogFold), LogFold)) + 
  geom_col(aes(fill = LogFold)) + 
  scale_fill_gradient2(low = "white", 
                       high = "blue", 
                       midpoint = median(df1$LogFold)) + 
  coord_flip() + 
  labs(x = "Tissue")

enter image description here

But I don't know that the color gradient really adds anything much in terms of interpreting the information. So here's the result without it, you be the judge:

df1 %>% 
  ggplot(aes(reorder(Tissue, LogFold), LogFold)) + 
    geom_col() + 
    coord_flip() + 
    labs(x = "Tissue") + 
    theme_classic()

enter image description here

like image 90
neilfws Avatar answered Mar 15 '23 02:03

neilfws