【问题标题】:How to display different y labels in the equations using stat_poly_eq of ggpmisc如何使用 ggpmisc 的 stat_poly_eq 在方程中显示不同的 y 标签
【发布时间】:2019-10-14 09:07:30
【问题描述】:

我正在尝试使用ggpmisc 的stat_poly_eq 函数在绘图上显示方程。

我的问题是如何通过 y1=... 和 y2=... 通过引用 key 参数来更改等式中的 y= ...。

我尝试在映射中添加 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)

【问题讨论】:

    标签: r ggplot2 ggpmisc


    【解决方案1】:

    我不太确定是否可以通过 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))
    

    【讨论】:

    • 非常好的工作!!我没有新建函数 ggplot_build 来修改 ggplot 的元素。非常感谢;)
    猜你喜欢
    • 1970-01-01
    • 2016-12-05
    • 2021-08-20
    • 2021-01-06
    • 2016-12-18
    • 1970-01-01
    • 1970-01-01
    • 2022-11-29
    • 1970-01-01
    相关资源
    最近更新 更多