将自定义图例添加到ggplot

时间:2017-11-30 23:35:47

标签: r plot ggplot2 legend

我制作了散点图,然后添加了回归线。我是ggplot2的新人,我不太了解如何添加传奇。我想要一个像scater情节那样的圈子说"数据"和一行说"回归"。我怎么能这样做?

library(ggplot2)

ggplot(mpg, aes(displ, cty)) + geom_point(shape = 1) +
  stat_smooth(method = "lm", formula = y ~ x, se = FALSE, colour = 1, size = 0.5) +
  theme_classic() + theme(panel.border = element_rect(colour = "black", fill=NA),
                          aspect.ratio = 1, axis.text = element_text(colour = 1, size = 12))

enter image description here

我想要的是:

enter image description here

1 个答案:

答案 0 :(得分:2)

自定义图例在ggplot中可能很难实现,因为系统主要基于"映射"您的数据到一个比例,然后使用它来创建图例。对于自定义图例,您可以使用aes()调用在图例中手动设置所需的标签,例如:

ggplot(mpg, aes(displ, cty)) + 
    geom_point(aes(shape = "Data")) +
    stat_smooth(aes(linetype = "Regression"), method = "lm", 
                formula = y ~ x, se = FALSE, colour = 1, size = 0.5) +
    scale_shape_manual(values = 1) +
    labs(shape = "", linetype = "") +
    theme_classic() + 
    theme(panel.border = element_rect(colour = "black", fill=NA),
          aspect.ratio = 1, axis.text = element_text(colour = 1, size = 12))