在ggplot2中手动选择色调/啤酒颜色

时间:2013-08-23 06:13:23

标签: r colors ggplot2 scale hue

我正在尝试使用R中的ggplot2库生成渐进式图。

“渐进式”的意思是,出于演示目的,我想一次一个地添加一条线,所以我生成一个多行多次的单个图,每个图都有一条额外的绘图线。 / p>

在ggplot2中,使用scale_colour_hue()可以很好地工作,除了每行的颜色从绘图变为绘图。我想保持颜色不变(即图1的第1行有颜色X,在图5中,第1行仍然有颜色X ......等)。我可以通过使用scale_colour_manual()手动声明颜色来实现这一点,但我觉得我受这些颜色(“红色”,“蓝色”等)的美学限制。我是否真的必须在色调调色板中找到每种颜色的十六进制值,或者是否有更简单的方法,我可以指示scale_colour_hue()函数在每次添加新行时以固定顺序使用其调色板?

谢谢,感谢您的帮助!

1 个答案:

答案 0 :(得分:3)

如果您事先知道要添加的总行数,则可以创建具有适当颜色和名称的比例,以便与scale_colour_manual一起使用

library(RColorBrewer)
library(plyr)
# a function to create a brewer palette of any length (kittens will be killed)
myBrewerPal <- function(pal = 'Spectral'){
  colorRampPalette(brewer.pal(name = pal, n = 11))
}

# function to create a named vector of colours for a given 
# vector x
create.palette <- function(x, pal = 'Spectral'){
  ux <- sort(unique(x))
  n <- length(ux)
  setNames(myBrewerPal(pal)(n), ux)

}

# create a manual scale with the named values part
myPal <- scale_colour_manual(name = 'Gear', values = create.palette(factor(mtcars$gear)))


# the base plot (no lines)
baseplot <- ggplot(mtcars, aes(x=hp, y = disp, colour = factor(gear))) + myPal
# 1 line
baseplot + geom_line(subset = .(gear==3))

enter image description here

# 2 lines (gear = 3 is consistent)
baseplot + geom_line(subset = .(gear %in% 3:4))

enter image description here