How to position annotations in bottom right corner with plotly

Viewed 444

How can I position a Plotly annotation in the bottom right corner, irrespective of the x-axis label lengths? The annotation should more or less appear on the same line as the x-axis title.

In the example you can play with the label length. As long as the labels fit horizontally, the setting works fine, but as soon as the labels are placed in a certain angle, they overlap with the annotation.

library(shiny)
library(plotly)
data <- mtcars

ui <- fluidPage(
  sliderInput("nbars", "Amount of Columns", 2, 32, 15),
  sliderInput("nchars", "Max Length of Labels", 2, 50, 20),
  plotlyOutput("plot")
)

server <- function(input, output, session) {
  output$plot <- renderPlotly({
    n <- input$nbars
    nlabs <- input$nchars
    data <- data[sample(seq.int(nrow(data)), n),]
    data$labels <- unlist(lapply(seq.int(n), function(x) {
      paste0(sample(LETTERS[1:26], nlabs, replace = TRUE), collapse = "")
    }))
    
    plot_ly(data = data) %>%
      add_trace(type = "bar", x=~labels, y=~mpg) %>%
      add_annotations(
        x = 1.03,
        xref = "paper", 
        y = -0.15, 
        yref = "paper",
        showarrow = FALSE,
        text = "© company GmbH") %>%
      plotly::layout(title = paste0("<b>Some fance title</b>\n<sup>(n=",400,")</sup>"),
                     margin = list(l = 60, r = 60, b = 50, t = 50, pad = 3),
                     xaxis = list(title = "xtitle"),
                     yaxis = list(title = "<b>ytitle</b>"))
  })
}

shinyApp(ui, server)
0 Answers
Related