【发布时间】:2020-06-09 16:20:54
【问题描述】:
我想在每个方面都有不同的注释(例如 p 值)(我的实际绘图的每个斜率一个 - 总共 6 个)。我想我已经阅读了所有关于注释方面的帖子,最有用的当然是主要的Annotating text on individual facet in ggplot2。但在我的情况下,它会抛出错误。
我正在使用interactions 包,它提供了一个可编辑的ggplot 对象,但会带来其他问题。这是一个使用mtcars 的最小可重复示例。
# Create the model
mod1 <- lm(wt ~ am * drat * vs, data = mtcars)
# Make the plot
require(interactions)
(p <- interact_plot(mod1,pred="am",modx="drat",mod2="vs"))
# Make annotations dataframe
(dat_text <- data.frame(
text = c("p-value 1", "p-value 2"),
vs = c(0, 1)))
# Add annotations to dataframe
require(ggplot2)
p + geom_text(
data = dat_text,
mapping = aes(x = -Inf, y = -Inf, label = text),
hjust = -0.1,
vjust = -1
)
这给出:Error in FUN(X[[i]], ...) : object 'modx_group' not found。 'drat' not found 也有同样的错误。我不太确定如何解决这个错误(例如,将它们设置为什么值),所以我尝试将这些列添加到数据框中,如下所示:
# Make annotations dataframe
(dat_text <- data.frame(
text = c("p-value 1", "p-value 2"),
vs = c(0, 1),
modx_group = c("-1 SD", "+ 1 SD"), # Here ***
drat = c(-1,1))) # Here ***
# Add annotations to dataframe
p + geom_text(
data = dat_text,
mapping = aes(x = -Inf, y = -Inf, label = text),
hjust = -0.1,
vjust = -1
)
但这给出了:Insufficient values in manual scale. 4 needed but only 3 provided。将modx_group 和drat 设置为NA 或NA_real_ 甚至0,如this other post 所示,会引发另一个错误:Discrete value supplied to continuous scale。
在当前上下文中我无法理解这些错误。当然,我怀疑这与interactions 情节对象的时髦有关。也可能有一些明显的我做错了但看不到。任何帮助将不胜感激!
编辑
根据@stefan 的回答,我能够为我更复杂的设计创建所需的输出(有 6 个 p 值,每个斜率一个,每个注释的特定位置),如下所示。
<!-- language-all: lang-r -->
# Create the model
mod1 <- lm(wt ~ am * drat * vs, data = mtcars)
# Make the plot
require(interactions)
#> Loading required package: interactions
(p <- interact_plot(mod1,pred="am",modx="drat",mod2="vs"))
# Make annotations dataframes
dat_text <- data.frame(
text = c("p-value 3", "p-value 6", "p-value 2", "p-value 5", "p-value 1", "p-value 4"),
mod2_group = c("vs = 0", "vs = 1", "vs = 0", "vs = 1", "vs = 0", "vs = 1"),
x = c(0.5, 0.5, 0.5, 0.5, 0.5, 0.5),
y = c(3, 2.5, 3.5, 2.75, 4, 3))
# Add annotations to dataframe
require(ggplot2)
#> Loading required package: ggplot2
p + geom_text(data = dat_text,
mapping = aes(x = x, y = y, label = text),
inherit.aes = FALSE)
由reprex package (v0.3.0) 于 2020-06-10 创建
【问题讨论】:
标签: r ggplot2 facet interaction annotate