在不改变GGPLOT2改变颜色的传奇名(Changing legend names without

2019-08-03 23:59发布

我想在不改变已经被设定的自定义颜色重命名一个传奇的值。 有没有一种方法来设置图例标签不使用scale_color_manual? 目前,我有这样的事情:

norm <- rnorm(1000, 0 , .5)
gam <- rgamma(1000, 2)
beta <- rbeta(1000, 2, 3)
dist <- data.frame(Normal = norm, Gamma = gam, Beta= beta)
dat <- melt(dist, variable.name = "Distribution", value.name = "XValue")
plot1 <- ggplot(dat, aes(XValue, color = Distribution)) +
            stat_density(geom = "path", position = "identity", size = 2) +
            scale_color_manual(values = c("yellow", "black", "forestgreen"))

plot2 <- plot1 + scale_color_discrete(labels = c("Distribution 1",
                                "Distribution 2",
                            "Distribution 3"))

然而,这将覆盖手动颜色。 我会从那里我设置颜色,因此,不幸的是,我将无法使用scale_color_manual要更改其名称,在不同的功能(值= .​​..,标签= ...)。 我想到了另一种选择是以某种方式得到plot1使用的颜色。 然后我可以这样做:

colors <- plot1$colors_used
plot2 <- plot1 + scale_color_manual(labels = c("Distribution 1", 
                                               "Distribution 2",
                        "Distribution 3"),
                                      values = colors)

任何帮助将非常感激。 谢谢!

Answer 1:

它可以指定在标签名称scale_colour_manual

ggplot(dat, aes(XValue, color = Distribution)) +
  stat_density(geom = "path", position = "identity", size = 2) +
  scale_color_manual(values = c("yellow", "black", "forestgreen"),
                     labels = c("Distribution 1",
                                "Distribution 2",
                                "Distribution 3"))



Answer 2:

接下来是不能保证在所有情况下工作的一个可怕的,可怕的念头:

plot1$scales$scales[[1]]$labels <- c("Distribution 1","Distribution 2","Distribution 3")

愿上帝保佑你的灵魂吧。

没有人愿意重构他们的代码。 但是,当你已经到了一个地步明显,简单的解决方案的一个问题是突然不可能的,因为现有的代码库的复杂性完全,这是正确的行动路线。

另外,稍差进攻选择:

levels(dat$Distribution) <- c("Distribution 1","Distribution 2","Distribution 3")
plot1 %+% dat


Answer 3:

如果你愿意使用一致的调色板,那么你可以将此定义为:

    mycolors <- c("red", "blue", "black", #ee4747, #fff382, #f1f6c8, #334d65, #263825)

现在,而不是

    values = c("yellow", "black", "forestgreen")

使用

    values = mycolors


文章来源: Changing legend names without changing colors in ggplot2
标签: r ggplot2