首页 文章

将因子特定颜色添加到R中的截止线

提问于
浏览
2

我正在写一个函数来制作一个情节 . 该图将特定于组的相对平均偏差(分别为效应大小)与大样本平均值进行比较,并将每组的总体平均偏差显示为水平线 . 我已经研究了如何为绘图中的组获得不同的颜色,但是我不能让这些颜色也以其特定于组的颜色着色 .

这是一些示例数据:

a <- c(runif(10))
names(a) <- c(paste0("v", 1:10))
b <- c(runif(10))
names(b) <- c(paste0("v", 1:10))
c <- c(runif(10))
names(c) <- c(paste0("v", 1:10))

dev_list <- list(a,b,c)
names(dev_list) <- c("group1", "group2", "group3")

首先我融化数据:

require(reshape2)
df_aux <- data.frame(matrix(unlist(dev_list), nrow=length(dev_list), byrow=T), class = c(names(dev_list)))
colnames(df_aux) <- c(c(paste0("v", 1:10)), "class")
df_melt <- melt(df_aux)

然后我为截止线创建一个数据框:

ml_list <- mapply(function(A, B) {
  list(data.frame( x = c(-Inf, Inf), y = mean(A), cutoff = factor(paste(B, "Mean Deviation", sep = " "))))
}, dev_list, c(names(dev_list)))

然后我绘制数据:

require(ggplot2)
p <- ggplot(df_melt, aes(variable, value)) + geom_point(aes(colour = class))

到目前为止,这么好,但是当我现在插入行时,我不知道如何再次引用类变量来定义行的颜色 . 我的代码到目前为止:

p <- p + lapply(ml_list, function(z) {geom_line(aes(x,y, linetype = cutoff), z)})

之后的情节 p 看起来像这样:

Link to the plot as apparently I cannot include it in the post yet

我已经尝试将相同的 colour = class 放在geom_line的内部,但它没有尝试使用_2366574中解释的一些技术,但我无法工作 .

任何人都可以帮助我正确的颜色规范,以便我的最后一行代码使用类变量的颜色与绘图相同的方式?

提前致谢!

编辑:如果其他人需要这个:要使Brandons解决方案工作,您需要在上面的 ml_list 中包含颜色定义变量 .

新代码行:

ml_list <- mapply(function(A, B) {
    list(data.frame( x = c(-Inf, Inf), y = mean(A), cutoff = factor(paste(B, "Mean Deviation", sep = " ")), class = factor(paste0(B))))
    }, dev_list, c(names(dev_list)))

1 回答

  • 1

    我认为诀窍是将事物保存为data.frame . 单独添加图层有点痛苦,因为您还必须在每次应用时设置颜色*

    ml_list <- unique(do.call(rbind, ml_list)[-1])
    
    p <- ggplot(df_melt, aes(variable, value)) + geom_point(aes(colour = class))
    p + geom_hline(aes(yintercept=y, linetype = cutoff, color = cutoff), ml_list) + 
        scale_color_discrete(breaks = df_melt$class)
    

    设置 scale_color_discrete() 强制演示,我认为,这个剧情需要 .

相关问题