簡體   English   中英

如何在R中的ggplot2中添加自定義圖例

[英]How to add a custom legend in ggplot2 in R

我想繪制一個數據集,其中點的大小與x變量成比例,並且具有回歸線和95%的預測間隔。 我編寫的“樣本”代碼如下:

  # 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

這將產生以下圖:
ggplot產生的圖

顯然,圖例在這里並沒有太大幫助。 我想在圖例中輸入一個點,例如標記為“數據”,用一條灰色虛線標記為“ 95%PI”,用一條黑線標記為“回歸線”。

正如在提供的鏈接中提到的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"))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM