如何匹配R中多个ggplot2图形中的调色板?

时间:2013-12-17 02:50:42

标签: r ggplot2

已经有一段时间了,但是我知道我将很快提取新数据,我想弄清楚如何用这种技术绘制它。看起来评论和回答中的人都知道这可能是怎么回事,但我不能完全弄清楚给我什么。还有其他人想要解决这个问题吗?

我正在尝试使用具有多个级别的因子变量绘制多个条形图。

首先,我生成一个data.frame并创建一个因子,我按照数值降序(这样该图将从最高位移到最低位)。然后,我想生成一个ggplot2对象,在这种情况下可以是gg1。这将自动为每个级别指定颜色并构建条形图。然后我创建gg2,它基本上是相同的,但具有不同的顺序。但是,ggplot2会根据val的值自动分配颜色。我需要将颜色映射到字符串name,以便可以在多个ggplot对象中重复使用。

简而言之,问题在于,在下面的示例中,只有轴标记值会发生变化,而不是颜色。我尝试使用here方法来修改颜色无济于事。有什么想法吗?

library(ggplot2)
test1 <- data.frame(name = c('a', 'b', 'c'),
                    val = 1:3)
test1$name <- factor(test1$name,
                     levels = as.character(test1$name[order(-test1$val)]))
gg1 <- ggplot(data = test1) + geom_bar(aes(x = name, y = val, fill = val))
gg1
test2 <- data.frame(name = c('a', 'b', 'c'),
                    val = c(3, 1, 2))
test2$name <- factor(test2$name,
                     levels = as.character(test2$name[order(-test2$val)]))
gg2 <- ggplot(data = test2) + geom_bar(aes(x = name, y = val, fill = val))
gg2

这就是我尝试合并链接解决方案中建议的方法的方法:

g <- ggplot_build(gg1)
myPalette <- unique(g$data[[1]]["fill"])[, 1]
gg3 <- ggplot(data = test2) + geom_bar(aes(x = name, y = val, fill = val)) + 
       scale_fill_manual(values = myPalette)
gg3

1 个答案:

答案 0 :(得分:3)

试试这个

test2 <- data.frame(name = c('a', 'b', 'c'),
                    val = c(3, 1, 2,3,2,1,1,2,3))

为填充值添加标签

test2$val <- factor(test2$val,
                    levels = c(1,2,3),
                    labels = c("One", "Two","Three")) 
ggplot(data = test2) + geom_bar(aes(x = name,fill=val)) +
  scale_fill_manual(values = c('One' = "red", 'Two' = "orange", 'Three' = "blue"))
相关问题