簡體   English   中英

將相關性和 p 值添加到 plotly 圖表

[英]Adding correlation and p-value to a plotly chart

我使用 ggplot2 創建點 plot,然后將相關系數添加到該圖表。 接下來,我使用 plotly 查看有關每個數據點的信息。 但是這里顯示的plot字體樣式有誤。

我需要 R = 0.87 和 P = 2.2e-16,而不是“斜體(R)”或“斜體(P)”,同時將映射部分保留在 stat_cor 中。 我猜,plotly 無法將italic(p)部分理解為代碼。 解決方案不應該修復手動添加文本,我需要計算“R”和“P”。

這是代碼:

p1 <- ggplot(iris) +
      geom_point(aes(Sepal.Length, Petal.Length)) +
      stat_cor(mapping = aes(Sepal.Length, Petal.Length))
p2 <- ggplotly(p1)
p2

您可以向 plotly 圖表添加注釋 - 任何類型的 R 函數和 html 代碼都將作為文本的一部分工作。

Plotly唯一解

一個可能的解決方案是直接使用 plotly,而不是使用 ggplot 然后轉換。

代碼將是:

p2 <- plot_ly(data = iris, x=~Sepal.Length, y = ~Petal.Length) |>   #base R pipe operator
  add_annotations(
  xref = "paper", yref = "paper",
  x = 0.1, y = 0.9, 
  text = paste0("<i>R</i> = ", round(cor(iris$Sepal.Length, iris$Petal.Length),2), "<br>",
            "<i>P</i> = ", formatC(cor.test(iris$Sepal.Length, iris$Petal.Length)$p.value,
                                       format="e", digits=2)),
  showarrow = F,   # Does not show an arrow indicating the text position
  align = "left")  #align the text left
p2
  • "paper" 定義 x 和 y 如何應用(相對於軸(紙)或特定值)
  • x = 0.1, y = 0.9 表示文本將放置在 x 軸的 10% 和 y 軸的 90% 處。
  • 文本是文本本身。 我正在使用基本函數來計算 R 和 p 值,並使用 html 符號來編輯文本。

替代使用 ggplotly

由於您更喜歡使用 ggplotly,因此可以在其上使用完全相同的注釋。 在這種情況下,代碼是:

p1 <- ggplot(iris) + geom_point(aes(Sepal.Length, Petal.Length))
p2 <- ggplotly(p1) |>
      add_annotations(
        xref = "paper", yref = "paper",
        x = 0.01, y = 0.95, 
        text = paste0("<i>R</i> = ", round(cor(iris$Sepal.Length, iris$Petal.Length),2),
                      "<br>",
                      "<i>P</i> = ", formatC(cor.test(iris$Sepal.Length, iris$Petal.Length)$p.value,
                                            format="e", digits=2)),
      showarrow = F,   # Does not show an arrow indicating the text position
      align = "left")  #align the text left
p2

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM