首页 > 解决方案 > 如何在不创建多条回归线的情况下为 ggplot 中的变量着色?

问题描述

我正在创建一个 ggplot,我想通过它们来自的横断面为数据点着色。但是,当我使用colour=transect参数执行此操作时,我最终也会为每个样带生成一条回归线:

在此处输入图像描述

这是我的代码:

ggplot(data=leaf.data, 
       aes(x=distance.from.ecotone..m., y=mean.herbivory....,colour=transect)) +
  geom_point() +
  geom_smooth(method = "lm", na.rm = TRUE, fullrange= TRUE, aes=(group=1))+
  labs(x="Distance from Ecotone (m)", y="Mean Herbivory per Tree (%)",
       title="Herbivory as a Function of Distance from an Ecotone")

标签: rggplot2

解决方案


这可以通过对图层进行color局部美学来实现:geom_point

library(ggplot2)

set.seed(42)
leaf.data <- data.frame(
  distance.from.ecotone..m. = runif(30, 0, 30),
  mean.herbivory.... = runif(30, -5, 15),
  transect = factor(sample(1:5, 30, replace = TRUE))
)

ggplot(data=leaf.data, aes(x=distance.from.ecotone..m., y=mean.herbivory....)) +
  geom_point(aes(colour=transect)) +
  geom_smooth(method = "lm", na.rm = TRUE, fullrange= TRUE)+
  labs(x="Distance from Ecotone (m)", y="Mean Herbivory per Tree (%)",
       title="Herbivory as a Function of Distance from an Ecotone")
#> `geom_smooth()` using formula 'y ~ x'


推荐阅读