2017-02-27 2 views
0

Ich benutze Knitr unter Rstudio, um Berichte zu erstellen, und ich habe ein Problem, die Anmerkungen zu meistern, wenn ich ggplotly verwende.Etiketten (annotieren) in ggplot2 Grafiken werden nicht analysiert, wenn Sie ggplotly verwenden

Nachfolgend ist ein Beispiel für Code, der korrekt funktioniert, wenn ich eine ggplot2-Grafik mit korrekten Anmerkungen drucke, und wenn ich sie mit ggplotly drucke, bekomme ich die richtige Grafik, aber mit Anmerkungen nicht geparst.

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) 

Vielen Dank im Voraus für Ihre Vorschläge.

Antwort

1

Plotly verwendet HTML-Formatierungs-Tags für seine Texte.

Die folgende Funktion sollte das für Ihr Beispiel kümmern.

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

Der Text als scatter Spur mit mode: text hinzugefügt wird (nicht fragen, warum ....), so dass wir überschreiben Sie den Text und fixieren Position.

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

Dank Maximilian! Es ist eine knifflige Lösung. – abret

Verwandte Themen