Search code examples
rplotlyggplotly

ggplotly in R : change data label size


I have to convert a ggplot to a plotly. Naturally, the easiest way to do so seems to be using ggploty, but the font size change. No problem to get back to the good size for axis labels and title, but I cannot figure how to do this for data labels? Any ideas? I do prefer to keep the ggplot and wrap it with ggplotly (many other plots as well).

I tried the font from layout with no success:

library(ggplot2)
library(plotly)

tbl <- data.frame(
  indicateur = c("freq1", "freq2", "freq3" ),
  valeur = c(44, 78, 84)
)

ggplotly(
  ggplot(tbl) +
    geom_bar(aes(x = indicateur, y = valeur), stat = 'identity', fill = rgb(31, 119, 180, maxColorValue = 255)) +
    geom_text(aes(x = indicateur, y = valeur, label = valeur), vjust = -0.5) + 
    ylim(0, max(tbl$valeur)*1.1) +
    labs(x = "", y = "", title = "simple counting") +
    theme_bw() +
    theme(
      axis.line = element_blank(), 
      panel.border = element_blank(),
      plot.title = element_text(hjust = 0.5)
    )
  ) %>%
  layout(
    showlegend = FALSE, 
    textfont = list(size = 5), 
    titlefont = list(size = 12),
    xaxis = list(tickfont = list(size = 9))
  )

Thanks in advance for the help.


Solution

  • How about just passing size into geom_text? In addition, I do not believe all the layout adjustments are necessary. See the following:

    library(tidyverse)
    library(plotly)
    
    tbl <- data.frame(
      indicateur = c("freq1", "freq2", "freq3" ),
      valeur = c(44, 78, 84)
    )
    
    p_size_5 <- ggplot(tbl, aes(x = indicateur, y = valeur, label = valeur)) +
      geom_bar(stat = "identity", fill = rgb(31, 119, 180, maxColorValue = 255)) +
      geom_text(vjust = -0.5, size = 5) +
      labs(
        title = "simple counting (text 5)",
        x = NULL, y = NULL
      ) +
      theme_bw() +
      theme(
        axis.line = element_blank(),
        panel.border = element_blank(),
        plot.title = element_text(hjust = 0.5)
      )
    
    ggplotly(p_size_5)
    

    size 5

    p_size_2 <- ggplot(tbl, aes(x = indicateur, y = valeur, label = valeur)) +
      geom_bar(stat = "identity", fill = rgb(31, 119, 180, maxColorValue = 255)) +
      geom_text(vjust = -0.5, size = 2) +
      labs(
        title = "simple counting (text 2)",
        x = NULL, y = NULL
      ) +
      theme_bw() +
      theme(
        axis.line = element_blank(),
        panel.border = element_blank(),
        plot.title = element_text(hjust = 0.5)
      )
    
    ggplotly(p_size_2)
    

    size 2