【问题标题】:ggplot2, line types mismatched with specified in aes mappingggplot2,线型与 aes 映射中指定的不匹配
【发布时间】:2018-05-02 16:05:29
【问题描述】:

我为每条线指定线型,​​结果实线变为点线,点线变为实线。我尝试使用实线、虚线和点线,但仍然无法弄清楚图中显示的线型的顺序是什么。下面是代码:

library(ggplot2)
library(ggthemes)

p = ggplot(data = msleep, aes(x = log(bodywt), y = sleep_total)) + 
  geom_point() + #' This time we will vary the feeding groups by shapes instead of colors
  geom_smooth(method='lm')

gg_data <- ggplot_build(p)


sleepplot2 = ggplot(data = msleep, aes(x = log(bodywt), y = sleep_total)) + 
  geom_point(shape=4, size=3, color='blue') + #' This time we will vary the feeding groups by shapes instead of colors
  geom_text(aes(label=name), nudge_x = 0.5, nudge_y = 1) +
  labs(x = "Log body weight (Kg)", y = "Time asleep (hrs/day)") +
  ggtitle('Housing 1990-2007') +
  geom_line(color='red', data = gg_data$data[[2]], mapping=aes(x = x, y = ymin, linetype='solid'), size = 0.5) +
  geom_smooth(color='red',data = msleep, mapping=aes(x = log(bodywt), y = sleep_total, linetype='dotted'), method='lm', se = FALSE, size=0.5) +
  geom_line(color='red', data = gg_data$data[[2]], mapping=aes(x = x, y = ymax, linetype='solid'), size = 0.5) +
  scale_linetype_manual('', values = c("solid","dotted"),labels=c("Fit: y=0.3*x", "95% conf. bounds"))

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    运行以下代码:(与您的代码相同,但不使用ggtheme 包)

    library(ggplot2)
    
    ggplot(data = msleep, aes(x = log(bodywt), y = sleep_total)) + 
      geom_point() +
      geom_smooth(method='lm')
    
    ggplot(data = msleep, aes(x = log(bodywt), y = sleep_total)) + 
      geom_point(shape=4, size=3, color='blue') +
      geom_text(aes(label=name), nudge_x = 0.5, nudge_y = 1) +
      labs(x = "Log body weight (Kg)", y = "Time asleep (hrs/day)") +
      ggtitle('Housing 1990-2007') +
      geom_line(color='red', data = gg_data$data[[2]], mapping=aes(x = x, y = ymin, linetype='solid'), size = 0.5) +
      geom_smooth(color='red',data = msleep, mapping=aes(x = log(bodywt), y = sleep_total, linetype='dotted'), method='lm', se = FALSE, size=0.5) +
      geom_line(color='red', data = gg_data$data[[2]], mapping=aes(x = x, y = ymax, linetype='solid'), size = 0.5) +
      scale_linetype_manual('', values = c("dotted","solid"),labels=c("Fit: y=0.3*x", "95% conf. bounds"))
    

    为我们提供了以下情节:

    图例和情节上的三行似乎与您想要实现的情节一致。

    【讨论】:

    • 你有没有注意到,在你的图中,虚线应该是实线,实线应该是虚线?检查 aes 设置
    • 抱歉,请检查编辑后的答案。我只是在最后一行更改了"solid""dotted" 的顺序,我们得到了想要的情节。我不确定为什么会发生不匹配。检查ggplot2 的文档我没有找到与此相关的任何内容,但似乎最后一行覆盖了以前的设置,(因为如果我删除最后一行,那么线型将再次匹配错误,尽管 aes 设置)
    • 谢谢,我想我们已经找到了 ggplot2 的错误
    • @zouhx 您能否将您找到的用于对 scale_linetype_manual 行进行编码的文档链接给我?谢谢
    猜你喜欢
    • 1970-01-01
    • 2012-01-19
    • 1970-01-01
    • 2021-10-14
    • 1970-01-01
    • 1970-01-01
    • 2020-12-31
    • 2015-11-01
    • 2022-10-12
    相关资源
    最近更新 更多