Search code examples
rgraphicsannotationsfont-sizer-plotly

Changing the fontsize of annotation in R plotly


I would like to increase the size of text annotations on plotly figure. The solution I came up is on the below minimal code. However, once the number of digits increase through the value, the font size of text is not applied into all digit members in the same way. In order to show you the actual issue, I prepare a pseudo input data, so please do not concentrate on why there some silly numbers to be displayed. This issue looks a small point, but it heavily affects my fluctuated data visualisation which have various deep and top values in the sequence. Any idea about this?

Minimal code

library(plotly)

df <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/gapminderDataFiveYear.csv", stringsAsFactors = FALSE)
df <- df[which(df$year==2007 & df$continent=='Europe' & df$pop > 2.e6),]

#pseudo input data
temp_data <- c(c(1:5, 10:15, 100:105, 1000:1010))

fig <- plot_ly(df, type='bar', x = ~country, y = temp_data, text = temp_data, name="",
               textposition = 'outside', #'auto' 
               textangle    = -90,
               textfont     = list(size = 120)
               )

fig

Current output

enter image description here

The expectation is something like that

enter image description here


Solution

  • You can do that by using layout. To accommodate the numbers, I also increased the y axis range.

    library(plotly)
    #> Loading required package: ggplot2
    #> 
    #> Attaching package: 'plotly'
    #> The following object is masked from 'package:ggplot2':
    #> 
    #>     last_plot
    #> The following object is masked from 'package:stats':
    #> 
    #>     filter
    #> The following object is masked from 'package:graphics':
    #> 
    #>     layout
    
    df <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/gapminderDataFiveYear.csv", stringsAsFactors = FALSE)
    df <- df[which(df$year==2007 & df$continent=='Europe' & df$pop > 2.e6),]
    
    #pseudo input data
    temp_data <- c(c(1:5, 10:15, 100:105, 1000:1010))
    
    fig <- plot_ly(df, type='bar', x = ~country, y = temp_data, text = temp_data, name="",
                   textposition = 'outside', #'auto'
                   textangle    = -90) %>% layout(yaxis=list(range=c(0, max(temp_data)+200)),
                                                  uniformtext=list(minsize=18, mode='show'))
    fig
    

    Created on 2020-05-27 by the reprex package (v0.3.0)