ggplot2:如何在不同的图中使用相同的颜色来获得相同的因子

Jer*_*Who 18 r ggplot2

如何在不同的图中将相同的颜色固定到一个值?

假设我有两个data.frames df1和df2:

library(ggplot2)
library(gridExtra)

set.seed(1)
df1 <- data.frame(c=c('a', 'b', 'c', 'd', 'e'), x=1:5,  y=runif(5))
df2 <- data.frame(c=c('a', 'c', 'e', 'g', 'h'), x=1:5,  y=runif(5))
Run Code Online (Sandbox Code Playgroud)

当使用c作为颜色指示器绘制它们时,我得到相同的五种颜色.

g1 <- ggplot(df1, aes(x=x, y=y, fill=c)) + geom_bar(stat="identity")
g2 <- ggplot(df2, aes(x=x, y=y, fill=c)) + geom_bar(stat="identity")
grid.arrange(g1, g2, ncol=2)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

但我希望c的相同值得到相同的颜色.

ags*_*udy 15

您可以使用设置自己的填充比例scale_fill_manual.我创建了一个带有颜色和不同值"c"的命名向量.

dd <- union(df1$c,df2$c)
dd.col <- rainbow(length(dd))
names(dd.col)  <- dd
Run Code Online (Sandbox Code Playgroud)

然后 :

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)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


Jer*_*Who 9

我现在写了一个函数,它生成另一个计算颜色的函数.我不确定这是不是一个好方法.评论赞赏.

library(ggplot2)
library(gridExtra)
library(RColorBrewer)

makeColors <- function(){
  maxColors <- 10
  usedColors <- c()
  possibleColors <- colorRampPalette( brewer.pal( 9 , "Set1" ) )(maxColors)

  function(values){
    newKeys <- setdiff(values, names(usedColors))
    newColors <- possibleColors[1:length(newKeys)]
    usedColors.new <-  c(usedColors, newColors)
    names(usedColors.new) <- c(names(usedColors), newKeys)
    usedColors <<- usedColors.new

    possibleColors <<- possibleColors[length(newKeys)+1:maxColors]
    usedColors
  }
} 

mkColor <- makeColors()


set.seed(1)
df1 <- data.frame(c=c('a', 'b', 'c', 'd', 'e'), x=1:5,  y=runif(5))
df2 <- data.frame(c=c('a', 'c', 'e', 'g', 'h'), x=1:5,  y=runif(5))

g1 <- ggplot(df1, aes(x=x, y=y, fill=c)) + geom_bar(stat="identity") + scale_fill_manual(values = mkColor(df1$c))
g2 <- ggplot(df2, aes(x=x, y=y, fill=c)) + geom_bar(stat="identity") + scale_fill_manual(values = mkColor(df2$c))
grid.arrange(g1, g2, ncol=2)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


Pau*_*tra 8

要制作这种复合图,请注意以下ggplot2几点:

df1$id = 'A'
df2$id = 'B'
df_all = rbind(df1, df2)
ggplot(df_all, aes(x=x, y=y, fill=c)) + 
    geom_bar(stat="identity") + 
    facet_wrap(~id)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

使用构面时,ggplot2将两个图都视为一个整体,保持颜色值映射相同.

  • 就在我的例子中,我将两个情节放在一起.我真正的问题包括许多独立的情节. (3认同)