Search code examples
rannotationsplotlyfigurer-plotly

Maintain keeping text size the same on zooming on plotly [R]


It might be pretty simple for seniors on R but I could not find any solution over plotly documentation and forums. Basically, even the user zoomed in/out throughout the figure, the size of the example text (as in below code: "Example Text") should be kept in the same size without zooming in and out of this text part only, including the locations etc similar to watermark idea. Zooming in/out should not be disabled for the figure entirely, just for this text. Any suggestions? Thanks in advance

library(plotly)

density <- density(diamonds$carat)

fig <- plot_ly(x = ~density$x, y = ~density$y, type = 'scatter', mode = 'lines', fill = 'tozeroy')
fig <- fig %>% layout(xaxis = list(title = 'Carat'),
                      yaxis = list(title = 'Density'),
                      annotations=list(text="Example Text", "showarrow" = F, font=list(size = 40))
                      )
fig

Solution

  • I realised that yref = "paper" and xref = "paper" allow us to specify a position that is always relative to the plot. y=1 refers to the top of plot and y=0 refers to the bottom of the plot. Similarly, x=1 refers to the right of plot and x=0 refers to the left of the plot. See details here. Based on that, I have modified the code as below. It is working perfectly as seen on 2 and 3.

    Without zoom in/out After zoom in

    Modified code

    library(plotly)
    
    density <- density(diamonds$carat)
    
    fig <- plot_ly(x = ~density$x, 
                   y = ~density$y, 
                   type = 'scatter', 
                   mode = 'lines', 
                   fill = 'tozeroy')
    fig <- fig %>% layout(xaxis = list(title = 'Carat'),
                          yaxis = list(title = 'Density'),
                          annotations=list(text="Example Text", 
                                           xref = "paper",
                                           yref = "paper",
                                           opacity = 0.4,
                                           "showarrow" = F, 
                                           font=list(size = 40)
                                           )
                          )
    fig