簡體   English   中英

向R中的geom_smooth添加自定義坡度並進行攔截

[英]Add custom slope and intercept to geom_smooth in R

我正在嘗試添加具有自定義截距和斜率的線。 我知道我可以使用geom_abline ,但是該線超出了繪圖的邊距。 我有以下數據。

>table 
intent observed true
      0     0.00 0.07
  .1-.3     0.19 0.19
  .4-.6     0.51 0.41
  .7-.9     0.79 0.48
      1     1.00 0.53

這是dput()

structure(list(intent = structure(c(4L, 1L, 2L, 3L, 5L), .Label = c(".1-.3", 
".4-.6", ".7-.9", "0", "1"), class = "factor"), observed = c(0, 
0.19, 0.51, 0.79, 1), true = c(0.07, 0.19, 0.41, 0.48, 0.53)), row.names = c(NA, 
-5L), class = "data.frame", .Names = c("intent", "observed", 
"true"))

這是我目前的解決方案

table %>% 
  ggplot(aes(y=true,x=observed))+
  geom_point()+
  geom_smooth(method = lm,se=F,color="black",lty=2,size=1/2)+
  geom_abline(intercept=0.07, slope=0.599,size=1/2)

在此處輸入圖片說明

問題在於geom_abline是參考線的一種。 因此,它超過了在0附近的圖邊距,並且在x軸上超過0.8時無法完全看到,這與geom_smooth相對,在圖區域中保持一條線。 如何在geom_smooth中使我的geom_abline工作,使其適合繪制區域。

您可以使用geom_segment()

library(ggplot2)
  ggplot(table, aes(y = true, x = observed)) + 
  geom_point() + 
  geom_smooth(method = lm, se = F, color = "black", lty = 2, size = 1 / 2) + 
  geom_segment(x = 0, y = 0.07, xend = 1, yend = 0.669, size = 1 / 2) +
  scale_y_continuous(limits = c(0, 0.7))

使用線性方程式計算yend參數:y = 0.07 + x0.599

0.07 + 0.599
[1] 0.669

暫無
暫無

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

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