首页 > 解决方案 > 有没有办法创建一个带有 n 种颜色的 ggplot 多面散点图,以便颜色交替或从调色板中随机化?

问题描述

我的数据集中有 40 个受试者,每组 4 个,我想创建一个图,显示每个受试者复制的一条线(3 个复制);按主题着色,通过复制塑造。我遇到的问题是每个方面(组)的颜色都非常相似,以至于我无法真正区分它们。

我的情节主要代码是:

ggplot(T_S, aes(x=as.numeric(Day), y=variable, colour=as.factor(Subj))) +
    geom_point(aes(shape=as.factor(Rep))) +
        geom_line(aes(linetype=as.factor(Rep))) +
            facet_wrap(.~Group,ncol=3) +
                 theme_bw() +
                    theme(legend.position="none")

下面使用 viridis 包来说明我无法区分颜色的意思。有没有办法让颜色在每个面内的深紫色和黄色之间交替?

[Viridis 包示例][1]

我尝试过的其他事情:

我还研究了 PolyChrome 和 randomcolorR 包,但看不到它们如何与 ggplot2 一起使用。任何其他建议也欢迎!在此先感谢您的帮助。[1]:https ://i.stack.imgur.com/2iHXY.png

标签: rggplot2colorsfacetsubject

解决方案


似乎可以通过“RColorBrewer”包通过不同调色板的颜色组合来完成。

使用来自 Allan Cameron 的模拟数据:

require(ggplot2)
require(RColorBrewer)
set.seed(69)
    
T_S <- data.frame(Day      = rep(c(4, 11, 16, 25), 120),
                  Subj     = rep(1:40, each = 12),
                  Rep      = rep(rep(1:3, each = 4), 40),
                  Group    = factor(rep(1:10, each = 48), c(2:10, 1)),
                  variable = c(replicate(120, cumsum(runif(4, 0, 400)) + 250)))

现在我们可以组合来自不同调色板的颜色:

mycolours = c(brewer.pal(name="Accent", n = 7),
              brewer.pal(name="Dark2", n = 7),
              brewer.pal(name="Paired", n = 7),
              brewer.pal(name="Set3", n = 7),
              brewer.pal(name="Dark2", n = 7),
              brewer.pal(name="Set1", n = 7))

在这种情况下,调色板并不重要,但我试图选择它们以使它们脱颖而出。这里有关于调色板的完整详细信息的很好的文档:https ://www.datanovia.com/en/blog/the-az-of-rcolorbrewer-palette/ 。也可以选择更多或更少的颜色,在这种情况下有 42 种。如果您需要说,例如 1000 种颜色,可能会出现问题,因为这个包中没有那么多颜色。

最后是绘制数据的代码:

ggplot(T_S, aes(x=as.numeric(Day), y= variable, colour = as.factor(Subj))) +
  geom_point(aes(shape = as.factor(Rep))) + 
  geom_line(aes(linetype = as.factor(Rep))) +
  facet_wrap(.~Group, ncol = 3) +
  theme_bw()  +
  theme(legend.position="none") +
  scale_color_manual(values = mycolours)

https://imgur.com/fGsXy4k

国标


推荐阅读