簡體   English   中英

ggplot2 顯示帶有 geom_abline 和 geom_smooth 的圖例

[英]ggplot2 show legends with geom_abline and geom_smooth

我正在嘗試使用以下代碼為 geom_smooth 和 geom_abline 生成圖例

ggplot(data = d, aes(x = log(x), y =log(y) )) +
  geom_hex() +
  geom_smooth(method='lm',formula=y~x, color = "red", show.legend=TRUE) +
  geom_abline(color = "green", show.legend=TRUE) +
  scale_colour_manual(name='Lines', values=c("Regression", "Abline"))+
  theme_bw() 

我在這里看到了一個相關的問題: ggplot2 legend for abline 和 stat_smooth ,但沒有一個推薦的解決方案生成圖例。 有任何想法嗎?

一些假數據:

x <- c(4.17,5.58,5.18,6.11,4.50,4.61,5.17,4.53,5.33,5.14)
y <- c(4.81,4.17,4.41,3.59,5.87,3.83,6.03,4.89,4.32,4.69)
d <- data.frame(x = x, y = y)

編輯:按照卡米爾的建議,我添加了 aes() 環繞顏色,但無濟於事。

ggplot(data = d, aes(x = log(x), y =log(y) )) +
  geom_hex() +
  geom_smooth(method='lm',formula=y~x, aes(color = "red"), show.legend=TRUE) +
  geom_abline(aes(color = "green"), show.legend=TRUE) +
  scale_colour_manual(name='Lines', values=c("Regression", "Abline"))+
  theme_bw() 

這適用於 geom_smooth 線,但現在 geom_abline 說:“錯誤:geom_abline 需要以下缺失的美學:斜率,截距”

這是一個選項

ggplot(data = d, aes(x = log(x), y =log(y) )) +
  geom_hex() +
  geom_smooth(method='lm',formula=y~x, aes(color = "red")) +
  geom_abline(aes(slope = 1, intercept = 0, color = "green"), show.legend=FALSE) +
  scale_colour_manual(name='Lines',
                      labels = c("Abline", "Regression"), 
                      values=c("green", "red")) +
  theme_bw()

當我們映射color"green"里面geom_abline ggplot抱怨

錯誤:geom_abline 需要以下缺失的美學:斜率、截距

這就是為什么我也必須包括這些美學。

在此處輸入圖片說明

暫無
暫無

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

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