ggplot2: How to use same colors in different plots for same factor

前端 未结 3 836
春和景丽
春和景丽 2020-11-30 09:45

How can I pin the same color to a value in diffent plots?

Say I have two data.frames df1 and df2:

library(ggplot2)
library(gridExtra)

set.seed(1)
d         


        
3条回答
  •  囚心锁ツ
    2020-11-30 10:34

    You can set your own fill scale using scale_fill_manual. I create a named vector with colors and different values of "c".

    dd <- union(df1$c,df2$c)
    dd.col <- rainbow(length(dd))
    names(dd.col)  <- dd
    

    Then :

    g1 <- ggplot(df1, aes(x=x, y=y, fill=c)) + 
      geom_bar(stat="identity") +
      scale_fill_manual("Legend", values = dd.col)
    g2 <- ggplot(df2, aes(x=x, y=y, fill=c)) + 
      geom_bar(stat="identity") +
      scale_fill_manual("Legend", values = dd.col)
    grid.arrange(g1, g2, ncol=2)
    

    enter image description here

提交回复
热议问题