【问题标题】:How to set the color range of scale_colour_brewer() in ggplot2? (palette selected)如何在ggplot2中设置scale_colour_brewer()的颜色范围? (已选择调色板)
【发布时间】:2015-06-10 13:17:07
【问题描述】:

很抱歉,由于我在此网站上的声誉有限,我无法提供图片...

我使用以下代码在 R 中生成我的折线图:

p <- ggplot()+
geom_line(data=data, aes(x, y, color=Label))+ scale_colour_brewer(palette="Oranges")

我使用调色板“橙色”是因为我想生成一系列颜色相似但颜色不同的线条。

但是,下限/上限范围的颜色太浅,所以我想为调色板设置一个限制以避免颜色发白。

我知道我应该指定类似scale_color_gradient(low = "green", high = "red") 的内容,但是如何使用给定的调色板找到指定的颜色?

非常感谢!

【问题讨论】:

    标签: r ggplot2 colorbrewer


    【解决方案1】:

    由于您有一个离散的比例,您应该能够手动创建颜色集并使用 scale_color_manual 而不会有太多麻烦。

    library(ggplot2)
    theme_set(theme_bw())
    fake_data = data.frame(
        x = rnorm(42), 
        y = rnorm(42), 
        Label = rep(LETTERS[1:7], each = 6))
    
    p_too_light <- ggplot()+ geom_line(data=fake_data, aes(x, y, color=Label))+ 
      scale_colour_brewer(palette="Oranges")
    p_too_light
    

    现在使用 brewer.pal 和 http://www.datavis.ca/sasmac/brewerpal.html。

    library(RColorBrewer)
    my_orange = brewer.pal(n = 9, "Oranges")[3:9] #there are 9, I exluded the two lighter hues
    
    p_better <- ggplot()+ geom_line(data=fake_data, aes(x, y, color=Label))+ scale_colour_manual(values=my_orange)
    p_better
    

    如果您有超过 6 个类别,您可以使用 colorRampPalette 与之前 brewer.pal 调用中的边界颜色。然而,现在选择调色板方案需要更多的考虑(也许为什么 ggplot2 不会自动为离散比例执行此操作)。

    fake_data2 = data.frame(
      x = rnorm(140), 
      y = rnorm(140), 
      Label = rep(LETTERS[1:20], each = 7))
    
    orange_palette = colorRampPalette(c(my_orange[1], my_orange[4], my_orange[6]), space = "Lab")
    my_orange2 = orange_palette(20)
    
    p_20cat <- ggplot()+ geom_line(data=fake_data2, aes(x, y, color=Label))+
      scale_colour_manual(values=my_orange2)
    p_20cat
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-26
      • 1970-01-01
      • 2016-01-21
      • 2012-07-05
      • 2013-08-26
      相关资源
      最近更新 更多