如何在R中添加ggplot2中的自定义图例

问题描述:

我想绘制一个数据集,其中点的大小与x变量成比例并具有95%预测间隔的回归线。我写的“样本”,代码如下:如何在R中添加ggplot2中的自定义图例

# Create random data and run regression 
    x <- rnorm(40) 
    y <- 0.5 * x + rnorm(40) 
    plot.dta <- data.frame(y, x) 
    mod <- lm(y ~ x, data = plot.dta) 

    # Create values for prediction interval 
    x.new <- data.frame(x = seq(-2.5, 2.5, length = 1000)) 
    pred <- predict(mod,, newdata = x.new, interval = "prediction") 
    pred <- data.frame(cbind(x.new, pred)) 

    # plot the data w/ regression line and prediction interval 

    p <- ggplot(pred, aes(x = x, y = upr)) + 
    geom_line(aes(y = lwr), color = "#666666", linetype = "dashed") + 
    geom_line(aes(y = upr), color = "#666666", linetype = "dashed") + 
    geom_line(aes(y = fit)) + 
    geom_point(data = plot.dta, aes(y = y, size = x)) 
    p 

这将产生以下情节:
Plot produced by ggplot

显然,传说是没有太大的帮助在这里。我想在图例中有一个条目标记为“数据”,一条灰色,标有“95%PI”的虚线和一条标有“回归线”的黑色条目。

+1

的[添加传说GGPLOT2线图](http://*.com/questions/10349206/add-legend-to-ggplot2-line-plot) –

+0

HTTP可能的复制.ORG /电流/ scale_size.html –

由于在提供的链接中暗示了Hack-R,您可以设置scale_size()的中断和标签以使该图例更有意义。

您还可以通过在您的aes()中添加线型并使用scale_linetype_manual()设置值,中断和标签来为所有geom_line()呼叫构建图例。 //docs.ggplot2:

ggplot(pred, aes(x = x, y = upr)) + 
    geom_line(aes(y = lwr, linetype = "dashed"), color = "#666666") + 
    geom_line(aes(y = upr, linetype = "dashed"), color = "#666666") + 
    geom_line(aes(y = fit, linetype = "solid")) + 
    geom_point(data = plot.dta, aes(y = y, size = x)) + 
    scale_size(labels = c("Eensy-weensy", "Teeny", "Small", "Medium", "Large")) + 
    scale_linetype_manual(values = c("dashed" = 2, "solid" = 1), labels = c("95% PI", "Regression Line"))