2016-11-14 44 views
0

ポイントのサイズがx変数に比例し、95%予測間隔の回帰直線を持つデータセットをプロットしたいとします。次のように私が書いた「サンプル」のコードは次のとおりです。
Plot produced by ggplotggplot2でカスタム凡例を追加する方法R

もちろん、伝説がここでも有用ではありません。

# 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 

は、これは次のプロットを作成します。凡例には、「データ」とラベル付けされた1つの灰色の点線、「95%PI」というラベルの付いた点、「回帰線」という黒い線のある項目があります。

+1

[ggplot2ラインプロットに凡例を追加](http://stackoverflow.com/questions/10349206/add-legend-to-ggplot2-line-plot) –

+0

HTTPの可能性のある重複://docs.ggplot2 .org/current/scale_size.html –

答えて

2

Hack-Rが提供されたリンクで言及しているように、その凡例をより意味のあるものにするために、改行とラベルをscale_size()に設定することができます。

aes()に線種を追加し、scale_linetype_manual()を使用して値、改行、およびラベルを設定して、すべてのgeom_line()コールの凡例を作成することもできます。

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")) 
関連する問題