Set specific fill colors in ggplot2 by sign

后端 未结 1 1196
长情又很酷
长情又很酷 2021-02-05 11:45

Hi wanted to adjust the following chart so that the values below zero are filled in red and the ones above are in dark blue. How can I do this with ggplot2?

   m         


        
相关标签:
1条回答
  • 2021-02-05 12:26

    The way you structure your data is not how it should be in ggplot2:

    require(reshape)
    mydata2 = melt(mydata)
    

    Basic barplot:

    ggplot(mydata2, aes(x = variable, y = value)) + geom_bar()
    

    enter image description here

    The trick now is to add an additional variable which specifies if the value is negative or postive:

    mydata2[["sign"]] = ifelse(mydata2[["value"]] >= 0, "positive", "negative")
    

    ..and use that in the call to ggplot2 (combined with scale_fill_* for the colors):

    ggplot(mydata2, aes(x = variable, y = value, fill = sign)) + geom_bar() + 
      scale_fill_manual(values = c("positive" = "darkblue", "negative" = "red"))
    

    enter image description here

    0 讨论(0)
提交回复
热议问题