ggplot2:如何在不同的图中为相同的因子使用相同的颜色 [英] ggplot2: How to use same colors in different plots for same factor

查看:19
本文介绍了ggplot2:如何在不同的图中为相同的因子使用相同的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

Say I have two data.frames df1 and 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))

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

When plotting them using c as color-indicator I get the same five colors.

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)

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

But I want that same values of c get the same color.

推荐答案

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

I now wrote a function which generates another function which computes the colors. I'm not sure if it's a good way. Comments appreciated.

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)

这篇关于ggplot2:如何在不同的图中为相同的因子使用相同的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆