【问题标题】:Changing color of data points in ggplot改变ggplot中数据点的颜色
【发布时间】:2017-08-15 19:51:46
【问题描述】:

首先我运行这段代码,它运行良好(所有数据点都变成蓝色):

ggplot(data = mpg) + geom_point(mapping = aes(x = displ, y = hwy), color = "blue")

但是当我尝试像下面那样移动映射时,数据点变成黑色而不是蓝色。

这是为什么呢?

ggplot(data = mpg, mapping = aes(x = displ, y = hwy), color = "blue") + geom_point() 

【问题讨论】:

  • 试试ggplot(data = mpg, mapping = aes(x = displ, y = hwy)) + geom_point(color = "blue")
  • @G5W 的评论完全正确。只是为了让您对此有更多了解;想象一下,您还想用线 (geom_line) 连接点,并且希望线是 red。这就是你实现它的方式:ggplot(data = mpg, aes(x = displ, y = hwy)) + geom_point(color = "blue") + geom_line(color="red")。您可以对所有 geoms 使用相同的映射 (aes)。

标签: r ggplot2 aesthetics


【解决方案1】:

您可以在几何图形之间共享映射内部的变量。特别是关于color,当设置为常量(例如"blue")而不是变量(此处解释:Answer to: When does the argument go inside or outside aes)时,它需要在aes 之外和geom 中定义。

我在下面提供了几个例子来更好地说明这一点;

library(ggplot2)
## works fine for each geom 
ggplot(data = mpg, aes(x = displ, y = hwy)) + 
  geom_point(color = "blue") + 
  geom_line(color="red")

## doesn't work when not in the geom
ggplot(data = mpg, aes(x = displ, y = hwy), color = "blue") + 
  geom_point() 

## gets evaluated as a variable when in aes
ggplot(data = mpg, aes(x = displ, y = hwy)) + 
  geom_point(aes(color = "blue")) 

## can use a variable in aes, either in geom or ggplot function
ggplot(data = mpg, aes(x = displ, y = hwy)) + 
  geom_point(aes(color = model), show.legend = FALSE) 

【讨论】:

    猜你喜欢
    • 2023-03-16
    • 2018-08-25
    • 1970-01-01
    • 2020-11-27
    • 2022-11-25
    • 2016-03-28
    • 1970-01-01
    • 2016-03-22
    • 2014-05-18
    相关资源
    最近更新 更多