【问题标题】:Labels (annotate) in ggplot2 graphics are not parsed when using ggplotly使用 ggplotly 时不解析 ggplot2 图形中的标签(注释)
【发布时间】:2017-02-27 12:15:02
【问题描述】:

我在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)  

提前感谢您的建议。

【问题讨论】:

    标签: r ggplot2 knitr plotly


    【解决方案1】:

    Plotly 对其文本使用 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)
    }
    

    文本被添加为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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多