Search code examples
rggplot2geom-bar

How to make a bar chart showing a negative value in R?


I have data including negative value and wanna make a bar chart.

genotype<-c("A","B","C")
treatment<- c("tr1", "tr2")
y<- c(-0.124, -0.083, -0.07, 0.130, 0.216, 0.182)

data1<- data.frame (genotype, treatment, y)

   genotype treatment      y
1        A       tr1 -0.124
2        B       tr2  0.130
3        C       tr1 -0.083
4        A       tr2  0.216
5        B       tr1 -0.070
6        C       tr2  0.182

ggplot(data1, aes(x=genotype, y=y)) + 
  geom_bar (stat="identity") +
  scale_y_continuous(breaks = seq(-1,1,0.2),limits = c(-1,1))

enter image description here

This is the graph which I made but what I want is, like the below, to distinguish positive and negative value. Could you tell me how to do it? Many thanks!!!

enter image description here


Solution

  • Try this:

    library(ggplot2)
    #Code
    ggplot(data1, aes(x=genotype, y=y,fill=treatment)) + 
      geom_bar (stat="identity",position = position_dodge(0.9)) +
      scale_y_continuous(breaks = seq(-1,1,0.2),limits = c(-1,1))
    

    Output:

    enter image description here

    Or more customized:

    #Code 2
    ggplot(data1, aes(x=genotype, y=y,fill=treatment)) + 
      geom_bar (stat="identity",position = position_dodge(0.9)) +
      scale_y_continuous(breaks = seq(-1,1,0.2),limits = c(-1,1),
                         labels = scales::percent)+
      theme_bw()+
      theme(legend.position = 'bottom',
            axis.title.x = element_blank(),
            axis.text.x = element_blank(),
            axis.ticks.x = element_blank(),
            axis.text.y = element_text(color='black',face='bold'),
            legend.text = element_text(color='black',face='bold'),
            legend.title = element_text(color='black',face='bold'),
            axis.title.y = element_text(color='black',face='bold'))+
      scale_fill_manual(values=c('red','gray25'))
    

    Output:

    enter image description here