美文网首页
R中扩展调色板的简单方法

R中扩展调色板的简单方法

作者: R语言数据分析指南 | 来源:发表于2020-06-20 08:21 被阅读0次

    本文介绍如何使用colorRampPalette()函数扩展调色板,将用ggplot2提供实际示例。
    RColorBrewer中定义的色标具有固定数量的颜色
    例如,调色板中Set2有8种颜色。因此,如果您的数据包含8个以上的组,则ggplot2将返回如下警告:

    !在brewer.pal(n,pal)
    n太大,调色板Set2的最大允许值为8返回使用有多种颜色的所需调色板
    
    df <- iris[1:18, ]
    df$name <- 1:nrow(df)
    library(ggplot2)
    ggplot(df) + 
      geom_col(aes(name, Sepal.Length, fill = factor(Sepal.Length))) +
      scale_fill_brewer(palette="Set2") +
      theme_minimal() +
      theme(legend.position = "top")
    
    Rplot.png

    一种解决方案是使用colorRampPalette()可以扩展任何颜色列表的功能:

    library(RColorBrewer)
    nb.cols <- 12
    mycolors <- colorRampPalette(brewer.pal(8, "Set3"))(nb.cols)
    ggplot(df) + 
      geom_col(aes(name, Sepal.Length, fill = factor(Sepal.Length))) +
      scale_fill_manual(values = mycolors) +
      theme_minimal() +
      theme(legend.position = "top")
    
    Rplot01.png

    相关文章

      网友评论

          本文标题:R中扩展调色板的简单方法

          本文链接:https://www.haomeiwen.com/subject/cwqwxktx.html