Search code examples
rggplot2plotlyggplotly

Geom_text position with ggplotly


I have a large amount of graphs using ggplot2. When using ggplotly, my geom_text does not obey the ggplot() position. See chart below:

 library(data.table)
 library(tidyverse)
 url <- "https://raw.githack.com/fsbmat-ufv/stackExchange/main/df.csv"
 test <- fread(url)

 plot <- ggplot(test,
                aes(reorder(factor(UF), desc(Value)),
                    y = Value,
                    fill = UF,
                    text = paste("UF: ",UF,
                                 "<br>",
                                 "Value: ",paste0("R$",formatC(1000000000*Value, digits = 2, big.mark=',', format = 'f'))))) +
   geom_col(show.legend = FALSE) +
   geom_text(aes(label=Value),
             position = position_dodge(width = 0.9),
             vjust = -0.5,
             size = 3) +
   xlab("Federal Unit") +
   ylab("Amount Received") +
   theme_light()
 plotly::ggplotly(plot, tooltip = "text")%>%
   plotly::layout(showlegend = FALSE)

insert image description here

I tried several solutions, one of them was to use the style function of plotly with the textposition=’top’ option. However, my tooltip appears over the chart bars and I can't resolve it.

 plotly::ggplotly(plot, tooltip = "text")%>%
   plotly::style(textposition = "top") %>%
   plotly::layout(showlegend = FALSE)

insert image description here

The textposition option affects geom_text as well as tooltip.


Solution

  • One option would be to manually nudge the y position for the labels instead of using vjust:

    library(data.table)
    library(ggplot2)
    library(dplyr)
    
    url <- "https://raw.githack.com/fsbmat-ufv/stackExchange/main/df.csv"
    test <- fread(url)
    
    plot <- ggplot(
      test,
      aes(reorder(factor(UF), desc(Valor)),
        y = Valor,
        fill = UF,
        text = paste(
          "UF: ", UF,
          "<br>",
          "Value: ", paste0("R$", formatC(1000000000 * Valor, digits = 2, big.mark = ",", format = "f"))
        )
      )
    ) +
      geom_col(show.legend = FALSE) +
      geom_text(aes(label = Valor, y = Valor + .1),
        position = position_dodge(width = 0.9),
        vjust = .5,
        size = 3
      ) +
      xlab("Federal Unit") +
      ylab("Amount Received") +
      theme_light()
    
    plot
    

    enter image description here

    plotly::ggplotly(plot, tooltip = "text") %>%
      plotly::layout(showlegend = FALSE)
    

    enter image description here