如何使用ggpmisc的stat_poly_eq在方程式中显示不同的y标签

5
我正在尝试使用ggpmiscstat_poly_eq函数在图表上显示方程式。
我的问题是如何通过引用key参数将y=...改为y1=...y2=...中的值。
我尝试在映射中添加eq.with.lhs参数,但它不能识别该参数。我尝试将向量传递给eq.with.lhs参数,但它重叠了每个方程中的两个元素...
你有更好的想法吗?
在最后一种情况下,我可以自己计算方程系数,然后使用geom_text,但这似乎是解决问题的不太有效的方法。
以下是我的问题的示例代码:
data <- data.frame(x = rnorm(20)) %>% 
    mutate(y1 = 1.2*x + rnorm(20, sd=0.2),
           y2 = 0.9*x + rnorm(20, sd=0.3)) %>%
    gather(value = value, key = key, -x)  

ggplot(data, aes(x = x, y = value)) +
    geom_point(aes(shape = key, colour = key)) + 
    stat_poly_eq(aes(label = ..eq.label.., colour = key), 
                 formula = y  ~ poly(x, 1, raw = TRUE),
                 eq.x.rhs = "x",
                 # eq.with.lhs = c(paste0(expression(y[1]), "~`=`~"),
                 #                 paste0(expression(y[2]), "~`=`~")),
                 eq.with.lhs = paste0(expression(y[ind]), "~`=`~"),
                 parse = TRUE) +
    ylab(NULL)
1个回答

3

我不确定是否可以通过 ggpmisc 来实现,但您可以在绘图完成后更改数据,方法如下:

library(tidyverse)
library(ggpmisc)

data <- data.frame(x = rnorm(20)) %>% 
    mutate(y1 = 1.2*x + rnorm(20, sd=0.2),
           y2 = 0.9*x + rnorm(20, sd=0.3)) %>%
    gather(value = value, key = key, -x)  

p <- ggplot(data, aes(x = x, y = value)) +
    geom_point(aes(shape = key, colour = key)) + 
    stat_poly_eq(aes(label = ..eq.label.., colour = key), 
                 formula = y  ~ poly(x, 1, raw = TRUE),
                 eq.x.rhs = "x",
                 eq.with.lhs = paste0(expression(y), "~`=`~"),
                 parse = TRUE) +
    ylab(NULL)
temp <- ggplot_build(p)
temp$data[[2]]$label <- temp$data[[2]]$label %>% 
    fct_relabel(~ str_replace(.x, "y", paste0("y[", 1:2, "]")))
grid::grid.newpage()
grid::grid.draw(ggplot_gtable(temp))

example


1
非常好的解决方法!我不知道有函数ggplot_build可以修改ggplot的元素。非常感谢 ;) - AlexC

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接