2017-02-27 17 views
0

Rstudioでknitrを使用してレポートを作成し、ggplotlyを使用するときにアノテーションをマスターするのに問題があります。ggplot2グラフィックスのラベル(注釈)は解析されません

これ以降、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) 

ご協力いただきありがとうございます。

答えて

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

テキストがmode: textscatterトレースとして追加されます(....理由を聞いていない)ので、私たちは、テキストを上書きして位置を固定します。

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 

enter image description here

+0

おかげマクシミリアン!これは難しい解決策です。 – abret

関連する問題