简体   繁体   English

在ggplot2中使用aes()函数中的颜色

[英]Using colors in aes() function in ggplot2

I am new to ggplot2 . 我是ggplot2 I am trying to understand how to use ggplot . 我试图了解如何使用ggplot I am reading Wickham's book and still trying to wrap my head around how to use aes() function. 我正在读Wickham的书,仍然试图围绕如何使用aes()函数。 In a related thread, we discussed that we should try to avoid using variables inside aes() ie "Don't put constants inside aes() - only put mappings to actual data columns." 在一个相关的线程中,我们讨论过我们应该尽量避免在aes()使用变量,即“不要将常量放在aes() - 只将映射放到实际的数据列中。”

My objective is to observe the behavior of ggplots when we have color inside aes() for labeling (as described in Wickham's book) and also override the color to print the color. 我的目标是观察ggplots的行为,当我们在aes()有颜色用于标记时(如Wickham的书中所述)并且还覆盖颜色以打印颜色。

I started with this: 我从这开始:

library(ggplot2)
data(mpg)
ggplot(mpg, aes(displ, hwy)) +
  geom_point() +
  geom_smooth(aes(colour = "loess"), method = "loess", se = FALSE) +
  geom_smooth(aes(colour = "lm"), method = "lm", se = FALSE) +
  labs(colour = "Method")

This nicely plots graphs and labels them. 这很好地绘制图形并标记它们。 However, I am unhappy with the colors used. 但是,我对使用的颜色不满意。 So, I experimented with using overriding colors again: 所以,我再次尝试使用重写颜色:

windows()
ggplot(mpg, aes(displ, hwy)) +
  geom_point() +
  geom_smooth(aes(colour = "loess"), method = "loess", se = FALSE, color = "magenta") +
  geom_smooth(aes(colour = "lm"), method = "lm", se = FALSE, color = "red") +  
  labs(colour ="Method")

I added color = "red" and we can see that labs() or aes(color()) doesn't have any effect. 我添加了color =“red”,我们可以看到labs()aes(color())没有任何效果。 Why does this happen? 为什么会这样? I'm curious. 我很好奇。 I'd appreciate thoughts. 我很感激你的想法。

When you specify, the colour outside aes() gg_plot does not consider the color information being part of the data (and it overwrites previous information) , so there is no legend to display anymore. 指定时,aes()gg_plot外部的颜色不会将颜色信息视为数据的一部分(并且它会覆盖以前的信息),因此不再显示图例。

If you want to specify your own colors and keep the colour information as "relevant data" and not "display information", you should add a scale_colour_manual() command to specify the legend colours and leave the colour attribute in aes : 如果要指定自己的颜色并将颜色信息保留为“相关数据”而不是“显示信息”,则应添加scale_colour_manual()命令以指定图例颜色并将颜色属性保留为aes

ggplot(mpg, aes(displ, hwy)) +
    geom_point() +
    geom_smooth(aes(colour = "loess"), method = "loess", se = FALSE) +
    geom_smooth(aes(colour = "lm"), method = "lm", se = FALSE) +  
    labs(colour ="Method") + scale_colour_manual(values = c("loess" = "magenta", "lm" = "red"))

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM