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

时间:2017-09-14 19:26:12

标签: r shiny

我需要在闪亮的应用上将相关系数放在我的散点图上。下面是我用来说明我的问题的例子。相关文本没有在图上显示。该复选框似乎没有响应。我花了很长时间试图找出原因,但无法做到。任何人都可以让我知道我做错了什么?非常感谢你提前。

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

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

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

这是结果

enter image description here

相关问题