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

2020-06-20  本文已影响0人  R语言数据分析指南

本文介绍如何使用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
上一篇下一篇

猜你喜欢

热点阅读