更改图例名称而不更改ggplot2中的颜色 [英] Changing legend names without changing colors in ggplot2

查看:168
本文介绍了更改图例名称而不更改ggplot2中的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在不更改已设置的自定义颜色的情况下重命名图例中的值.有没有一种方法可以在不使用scale_color_manual的情况下设置图例标签?目前,我有这样的东西:

I would like to rename the values in a legend without altering the custom colors that have already been set. Is there a way to set legend labels without using scale_color_manual? Currently, I have something like this:

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(values = ...,labels = ...).我想到的另一个选择是以某种方式获得plot1中使用的颜色.然后,我可以做类似的事情:

This however overwrites the manual colors. I will be changing the names in a different function from where I am setting colors so, unfortunately, I will not be able to use scale_color_manual( values =... , labels = ...). The other option I thought of is to somehow get the colors used in plot1. I could then do something like:

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

任何帮助将不胜感激.谢谢!

Any help would be much appreciated. Thanks!

推荐答案

可以在scale_colour_manual中指定标签名称.

It is possible to specify the label names in 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"))

这篇关于更改图例名称而不更改ggplot2中的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆