簡體   English   中英

如果使用覆蓋文本,則不顯示 R ggplot2 geom_smooth line

[英]R ggplot2 geom_smooth line not displayed if overlay text used

當省略 aes(text) 時,我只能在 ggplot 或 plotly 中顯示回歸線。 顯示工具提示文本或回歸線,但不能同時顯示。 我真的很困惑為什么,因為 ggplot/ggplotly 沒有警告或錯誤。

Dataframe:

sum(is.na(cdata2))
[1] 0

str(cdata2)
'data.frame':   2508 obs. of  7 variables:
 $ POPESTIMATE2019: num  55869 223234 24686 22394 57826 ...
 $ ST             : chr  "AL" "AL" "AL" "AL" ...
 $ pdensity       : num  93 140 27 35 89 16 25 187 55 47 ...
 $ STC            : chr  "Alabama-Autauga" "Alabama-Baldwin" "Alabama-Barbour" "Alabama-Bibb" ...
 $ tcases         : int  132 264 92 51 47 58 301 136 329 30 ...
 $ tdeaths        : int  4 8 1 1 1 1 10 3 22 0 ...
 $ SAHdate        : Date, format: "2020-04-04" "2020-04-04" "2020-04-04" "2020-04-04" ...

s <- ggplot(cdata2, aes(x = pdensity,
                        y = tcases,
                        size = tdeaths,
                        color = SAHdate,
                        text=paste0(
                          "<br>St-County: ",STC,
                          "<br>Pop: ",POPESTIMATE2019,
                          "<br>Tot Cases: ",tcases,
                          "<br>People/sq mile: ", pdensity,
                          "<br>Tot Deaths: ", tdeaths))) +
  geom_point() +
  geom_smooth(method = "lm", na.rm = TRUE, inherit.aes = TRUE);s

結果是沒有回歸線。 沒有帶有ggplot和文本的回歸線

如果我注釋掉文本部分:

s <- ggplot(cdata2, aes(x = pdensity,
                        y = tcases,
                        size = tdeaths,
                        color = SAHdate)
  geom_point() +
  geom_smooth(method = "lm", na.rm = TRUE, inherit.aes = TRUE);s

回歸線如圖所示:

顯示了ggplot回歸線

我嘗試使用 plotly 使用大量變體:

fit <- lm(tcases~pdensity, data=cdata2)
ggplotly(s) %>%
 add_trace(x = ~pdensity, y = ~fitted(fit),data = cdata2,mode = 'lines') %>%
 add_lines(x = ~pdensity, y = ~fitted(fit),data = cdata2,mode = 'lines')

`geom_smooth()` using formula 'y ~ x'
Error in min(x, na.rm = na.rm) : invalid 'type' (list) of argument

我難住了!

我無法確切回答您為什么會出現這種行為,但您是正確的,而且……這很奇怪。 我用一個簡單的例子做了一些偵探工作: df <- data.frame(x=1:1000, y=rexp(1000)) 我調整了全局aes()術語,尋找線條何時消失。 結果如下:

g <- list(geom_point(), geom_smooth())

ggplot(df, aes(x,y)) + g  # control
ggplot(df, aes(x,y, text=x)) + g  # OK
ggplot(df, aes(x,y, text='x')) + g   # OK
ggplot(df, aes(x,y, text=paste(x))) + g  # NO LINE SHOWN

解決方法已經在您的代碼中,即在geom_smooth()中設置inherit.aes=FALSE 無論出於何種原因,它都不喜歡在text=美學中使用paste() 這意味着您必須在geom_smooth中重申您的xy美學,但它工作正常:

ggplot(df, aes(x,y, text=paste(x))) +
    geom_point() + geom_smooth(inherit.aes = FALSE, aes(x,y))

在此處輸入圖像描述

我嘗試在geom_point()中移動 "text=..." ,如下所示:

p = p + geom_point(aes(text = paste("ID ",sampleID))

雖然它會發出警告消息,但當我生成plotly時:

ggplotly(p)

它成功了。

暫無
暫無

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

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