使用scale_colour_brewer palette

时间:2017-02-27 17:24:59

标签: r ggplot2

我有一个可变数量的列,我想用scale_colour_brewer(palette = "RdYlGn").绘制如果我有五列,我得到的最高和最低因子的颜色是深绿色和深红色。

n <- 5 #number of variables
x <- 1:10
y <- runif(10*n)
cond <- rep(1:n, each = 10)
df1 <- data.frame(x,y)

ggplot(df1, aes(x=x, y=y)) +
    geom_line(aes(colour=factor(cond), group=factor(cond)),size=2)  +
    scale_colour_brewer(palette = "RdYlGn")  + theme_bw()

enter image description here 但是,如果我只有两列(n <- 2),我会得到中间的范围颜色。无论我的数据中有多少列,如何获得最高和最低因子的深红色和深绿色?

n <- 2 #number of variables
x <- 1:10
y <- runif(10*n)
cond <- rep(1:n, each = 10)
df1 <- data.frame(x,y)

ggplot(df1, aes(x=x, y=y)) +
    geom_line(aes(colour=factor(cond), group=factor(cond)),size=2)  +
    scale_colour_brewer(palette = "RdYlGn")  + theme_bw()

enter image description here

修改 最后,我修改了@paqmo的答案并使用了seq。默认情况下,seq选择极值并填充中间值。

n <- 2#number of variables
x <- 1:10
y <- runif(10*n)
cond <- rep(1:n, each = 10)
df1 <- data.frame(x,y)

ggplot(df1, aes(x=x, y=y)) +
            geom_line(aes(colour=factor(cond), group=factor(cond)),size=2) +
            scale_colour_manual(values = brewer.pal(11,"RdYlGn")[round(seq(from = 1, to = 11,length.out = n))] ) +
            theme_bw()

enter image description here

2 个答案:

答案 0 :(得分:2)

使用scale_colour_manual来选择所需调色板中的哪些值。您必须确保在执行此操作时加载Rcolorbrewer,因为ggplot2仅在您使用Rcolorbrewer参数时调用scale_colour_brewercolorRampPalette从酿酒师调色板中抓取颜色。

set.seed(1034)
n <- 2 #number of variables
x <- 1:10
y <- runif(10*n)
cond <- rep(1:n, each = 10)
df1 <- data.frame(x,y)

ggplot(df1, aes(x=x, y=y)) +
    geom_line(aes(colour=factor(cond), group=factor(cond)),size=2) +
    scale_colour_manual(values = colorRampPalette(brewer.pal(11,"RdYlGn"), bias = 2)(n)) +
    theme_bw()

enter image description here

 set.seed(1034)
    n <- 3 #number of variables
    x <- 1:10
    y <- runif(10*n)
    cond <- rep(1:n, each = 10)
    df1 <- data.frame(x,y)

    ggplot(df1, aes(x=x, y=y)) +
        geom_line(aes(colour=factor(cond), group=factor(cond)),size=2) +   
        scale_colour_manual(values = colorRampPalette(brewer.pal(11,"RdYlGn"), bias = 2)(n)) +
        theme_bw()

enter image description here

 set.seed(1034)
        n <- 4 #number of variables
        x <- 1:10
        y <- runif(10*n)
        cond <- rep(1:n, each = 10)
        df1 <- data.frame(x,y)

        ggplot(df1, aes(x=x, y=y)) +
            geom_line(aes(colour=factor(cond), group=factor(cond)),size=2) +
            scale_colour_manual(values = colorRampPalette(brewer.pal(11,"RdYlGn"), bias = 2)(n)) +
            theme_bw()

enter image description here

答案 1 :(得分:1)

你可以通过设置比限制更少的休息来破解它:

library(ggplot2)
set.seed(47)

df1 <- data.frame(x = 1:10, 
                  y = runif(20), 
                  cond = factor(rep(1:2, each = 10)))

ggplot(df1, aes(x = x, y = y, colour = cond)) +
    geom_line(size = 2)  +
    scale_colour_brewer(palette = "RdYlGn", 
                        breaks = 1:2, 
                        limits = seq(1,2, length.out = 5))