ggplot2:绘制具有一组相似颜色的离散因子

Mar*_*ius 4 plot r ggplot2

我正在尝试在绘制它们时提出一种表示数据集中每个因子的一致方法.因此,例如,每当我绘制涉及词性的内容时,我可以将"词性"的级别用不同的蓝色阴影表示:

eg.dat <- data.frame(rt=c(530, 540, 555), 
                     part.of.speech=c("Verb", "Noun", "Both")
                     )

ggplot(eg.dat, aes(part.of.speech, rt, fill=part.of.speech)) +
  geom_bar(stat="identity", colour="black") +
  scale_fill_manual(values=c("cyan", "blue", "darkblue")) 
Run Code Online (Sandbox Code Playgroud)

手动指定颜色

然而,为每个因素提供像这样的花哨的颜色名称是困难的,所以我一直在寻找更自动的解决方案.一个相当hackish的解决方法是使用alpha:

ggplot(eg.dat, aes(part.of.speech, rt, alpha=part.of.speech)) +
  geom_bar(stat="identity", colour="black", fill="blue") +
  scale_alpha_discrete(range=c(0.4, 1))
Run Code Online (Sandbox Code Playgroud)

使用alpha

但我一直想知道是否有更简单的方法可以选择这样的短程类似颜色.该scale_colour_gradient型功能ggplot2不独立因素,如这些工作,它似乎并不特别容易得到自定义颜色出来rainbowheat.colors.理想的功能是: shades(n, central_colour="blue")返回n颜色值.有关实现这一目标的最佳方法的任何建议吗?

mne*_*nel 10

scale_fill_discrete或者scale_fill_hue会这样做.您可以定义h,cl(色调,色度和亮度).有关?hcl详细信息,请参阅

例如.

ggplot(eg.dat, aes(part.of.speech, rt, fill=part.of.speech)) +
     geom_bar(stat="identity", colour="black") +
     scale_fill_discrete( h =c(220,260))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

scale_fill_hue 将给出相同的结果(在这种情况下).

您还可以使用scale_fill_brewer它使用RColorBrewer包并提供对colorbrewer调色板的访问

ggplot(eg.dat, aes(part.of.speech, rt, fill=part.of.speech)) +
     geom_bar(stat="identity", colour="black") +
     scale_fill_brewer(palette = 'Blues')
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • @Marius,Color Brewer"sequential"调色板经过优化,可以顺序完成并且分离得很好.您可以通过更改调色板编号轻松地尝试所有19种可能性:`scale_fill_brewer(type ="seq",palette = 1)` (2认同)