簡體   English   中英

使用ggplotly時,不會解析ggplot2圖形中的標簽(注釋)

[英]Labels (annotate) in ggplot2 graphics are not parsed when using ggplotly

我在Rstudio下使用knitr生成報告,並且在使用ggplotly時無法掌握批注。

此后是當我使用正確的注釋打印ggplot2圖形時代碼正常工作的示例,如果我使用ggplotly打印它,則可以獲得正確的圖形,但注釋未解析。

library(ggplot2)
library(plotly) 

lm_fit <- lm(Sepal.Length ~ Sepal.Width, data=iris)
summary(lm_fit)
formule <- sprintf("italic(y) == %.2f % + .2f * italic(x)",
                   round(coef(lm_fit)[1], 2), 
                   round(coef(lm_fit)[2], 2))
r_2 <- summary(lm_fit)$r.squared
r2  <- sprintf("italic(r)^2 == %.4f", r_2)

graph1 <- ggplot(iris, aes(x = Sepal.Width, y = Sepal.Length)) + 
    geom_point() +
    geom_smooth(method = 'lm', aes(fill = 'confidence'), alpha = 0.5) +
    annotate("text", 
             x=min(iris$Sepal.Width), 
             y=max(iris$Sepal.Length), 
             label=formule, 
             parse=TRUE, 
             hjust=0) +
    annotate("text", 
             x=min(iris$Sepal.Width), 
             y=max(iris$Sepal.Length) - 0.3, 
             label=r2, 
             parse=TRUE, 
             hjust=0) 

out.format <-  "html" # KO for the annotations ; they are not parsed.
out.format <-  "pdf"  # OK for the annotations.

if (out.format == "html") plotly::ggplotly(graph1) else print(graph1)  

預先感謝您的建議。

對其文本使用HTML格式標記。

下面的函數應在您的示例中解決。

fix_annotation <- function(old_text){
  new_text = gsub('==', '=', old_text)
  new_text = gsub(' \\* ', '&middot;', new_text)
  new_text = gsub('italic\\(([0-9a-zA-z]*)\\)', '<i>\\1</i>', new_text)
  new_text = gsub('\\^([0-9]*)', '<sup>\\1</sup>', new_text)
  return(new_text)
}

文本以以下mode: text添加為scatter跡線mode: text (不要問為什么...),因此我們覆蓋了文本並固定了位置。

p <- plotly::ggplotly(graph1)
for (i in 4:5) {
  p[['x']][['data']][[i]][['text']] <- fix_annotation(p[['x']][['data']][[i]][['text']])
  p[['x']][['data']][[i]][['x']] <- min(p[['x']][['data']][[1]][['x']]) + 0.1 * (max(p[['x']][['data']][[1]][['x']]) - min(p[['x']][['data']][[1]][['x']]))

}
p

在此處輸入圖片說明

暫無
暫無

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

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