在ggplot2中的aes()函数中使用颜色 [英] Using colors in aes() function in ggplot2

查看:778
本文介绍了在ggplot2中的aes()函数中使用颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是ggplot2的新手.我试图了解如何使用ggplot.我正在阅读Wickham的书,但仍在尝试如何使用aes()函数.在相关的线程中,我们讨论了应该避免在aes()中使用变量,即不要在aes()中放置常量-只能将映射放置到实际数据列中."

I am new to ggplot2. I am trying to understand how to use ggplot. I am reading Wickham's book and still trying to wrap my head around how to use aes() function. In a related thread, we discussed that we should try to avoid using variables inside aes() i.e. "Don't put constants inside aes() - only put mappings to actual data columns."

我的目标是观察在aes()中有颜色用于标记时ggplots的行为(如Wickham的书中所述),并且还覆盖颜色以打印颜色.

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.

我从这个开始:

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")

我添加了color ="red",我们可以看到labs()aes(color())没有任何作用.为什么会这样?我很好奇.我将不胜感激.

I added color = "red" and we can see that labs() or aes(color()) doesn't have any effect. Why does this happen? I'm curious. I'd appreciate thoughts.

推荐答案

指定后,aes()gg_plot外部的颜色不会将颜色信息视为数据的一部分(并且它会覆盖以前的信息),因此存在没有图例可显示.

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.

如果要指定自己的颜色并将颜色信息保留为相关数据"而不是显示信息",则应添加scale_colour_manual()命令以指定图例颜色并将color属性保留在aes中:

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:

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"))

这篇关于在ggplot2中的aes()函数中使用颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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