繁体   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