【问题标题】:unable to put correlation coefficient on scatter plot on shiny app无法将相关系数放在闪亮应用程序的散点图上
【发布时间】:2017-09-14 19:26:12
【问题描述】:

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

#--------------------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))

【问题讨论】:

    标签: r shiny


    【解决方案1】:

    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')
    )
    

    【讨论】:

      【解决方案2】:

      您也可以使用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'))
      

      这是结果

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-01-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-01-06
        • 1970-01-01
        • 2016-08-01
        相关资源
        最近更新 更多