【问题标题】:R ggplot order legend geom_smooth and geom_ablineR ggplot 顺序图例 geom_smooth 和 geom_abline
【发布时间】:2018-04-11 06:31:22
【问题描述】:

我发现很多其他帖子解释了如何手动更改 ggplot2 生成的图例顺序,我已经尝试了所有建议,但仍然无法找出答案......

在我的情节中,我显示了来自geom_smooth(带有lm 函数)的线性回归线和我使用geom_abline 任意拟合的另一条线。

ggplot(women, aes(x=height, y=weight)) +
  geom_point(size=3, shape = 21, color="black") +
  geom_smooth(method = "lm", aes(color= "fit2", linetype = "fit2"), lwd=1, se = FALSE, show.legend = F) + 
  geom_abline(aes(intercept = -100, slope = 3.5, color="fit1", linetype = "fit1")) +
  scale_colour_manual(name="Legend", values = c("fit1" = "blue", "fit2" = "red")) +
  scale_linetype_manual(name="Legend", values = c("fit1" = "solid", "fit2" = "dashed"))

这会自动生成带有“fit1”和“fit2”的图例,但我希望“fit2”显示在“fit1”上方。很多帖子建议在我的数据框中重新排序数据,比如d$a <- factor(d$a, levels = d$a),但由于我的geom_abline 是任意行,我不能这样做。我试过scale_fill_discrete(breaks=c("fit2","fit1"))guides(fill = guide_legend(reverse = TRUE)) 但都没有工作。有没有其他方法可以强制“fit2”显示在“fit1”上方?

【问题讨论】:

  • 不相关,但我认为斜率和截距的值超出了图表的限制。尝试coef(lm(weight ~ height, data = women)) 以获得正确的值。
  • @neilfws 哦,你是对的,我更改了斜率和截距的值,以便 fit1 线实际显示在图中。感谢您指出这一点!

标签: r ggplot2 legend


【解决方案1】:

ggplot2 在使用aes() 将变量(即列名)映射到几何(线、点 及其相关属性 - 颜色、大小)时效果最佳。当数据整洁时,您可以“免费”获得图例之类的东西。在 aes() 中看到变量的引用词通常不是一个好兆头。

因此,我会以不同的方式处理此任务:

  1. 使用lm() 进行线性回归
  2. 使用broom::augmentlm 输出创建数据框
  3. 使用dplyr::mutatefit1 创建一个新列
  4. tidyr::gather将数据整理成一个整齐的数据框
  5. fit1fit2 转换为可以重新排序的因子
  6. geom_line 颜色映射到fit1fit2

    library(tidyverse)
    library(broom)
    
    women %>% 
      lm(weight ~ height, data = .) %>% 
      augment() %>% 
      mutate(fit1 = 3.5 * height - 100) %>% 
      select(weight, height, fit2 = .fitted, fit1) %>% 
      gather(fit, value, -weight, -height) %>% 
      mutate(fit = factor(fit, levels = c("fit2", "fit1"))) %>%
      ggplot() + 
        geom_point(aes(height, weight)) + 
        geom_line(aes(height, value, color = fit))
    

【讨论】:

  • 谢谢,这正是我需要的!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-03
  • 2014-09-29
  • 1970-01-01
相关资源
最近更新 更多