繁体   English   中英

无法将相关系数放在闪亮的应用程序的散点图上

[英]unable to put correlation coefficient on scatter plot on shiny app

我需要将相关系数放在闪亮的应用程序的散点图上。 下面是我用来说明我的问题的示例。 相关文本只是不显示在图上。 该复选框似乎没有响应。 我花了很长时间试图弄清楚为什么,但是不能。 谁能让我知道我做错了什么? 提前非常感谢您。

#--------------------functions------------------------------------------
corr_eqn <- function(x,y, method='pearson', digits = 2) {
    corr_coef <- round(cor.test(x, y, method=method)$estimate, digits = digits)
    corr_pval <- tryCatch(format(cor.test(x,y, method=method)$p.value, 
                                 scientific=TRUE),
                          error=function(e) NA)
    paste(method, 'r = ', corr_coef, ',', 'pval =', corr_pval)
}

sca.plot <- function (cor.coef=TRUE) {
    df <- mtcars %>% filter(cyl==4)
    p<- df %>% 
        ggplot(aes(x=hp, y=mpg))+
        geom_point()+
        geom_smooth()
    if (cor.coef) {
        p<- p+geom_text(x=0.9*max(mtcars$hp),
                        y=0.9*max(mtcars$mpg),
                        label = corr_eqn(df[['hp']],df[['mpg']],
                                         method='spearman'))
    }
    return (p)    
}

#-------------------------ui----------------------------
ui <- fluidPage(
    sidebarLayout(
        sidebarPanel(
            checkboxInput('cor.cplot', 
                          label = h5('Correlation Coefficient'), value = TRUE)
        ),
        mainPanel(
            plotOutput('plot') 
            )
        )
    )
#---------------------------server---------------------------------

server <- function(input, output) {


    output$plot <- renderPlot ({
        sca.plot(cor.coef = input$cor.cplot)
    })
}


runApp(shinyApp(ui, server))

geom运行良好,文本最终超出了绘图的限制,因为位置是根据mtcars而不是df的最大值计算得出的。

这应该工作

p <- p + geom_text(
  x = 0.9 * max(df$hp),
  y = 0.9 * max(df$mpg),
  label = corr_eqn(df[['hp']], df[['mpg']],
                   method = 'spearman')
)

可能希望使用geom_label来提高可读性

p <- p + geom_label(
  x = 0.9 * max(df$hp),
  y = 0.9 * max(df$mpg),
  label = corr_eqn(df[['hp']], df[['mpg']],
                   method = 'spearman')
)

您也可以使用annotate() 另外,请注意,您可能希望使用绘图中的数据而不是整个数据集为文本设置xy 为此,您可以使用p$data$hp而不是mtcars$hp

p <- p + ggplot2::annotate("text", x= 0.9*max(p$data$hp, na.rm = T),
                           y = 0.9*max(p$data$mpg, na.rm = T), 
                           label = corr_eqn(df[['hp']],df[['mpg']],
                                            method='spearman'))

这是结果

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM