Search code examples
rplotlytreemap

Move title to left in plot_ly


Previously when creating plotly grapths I've been using ggploty(), but now I wanted to make a treemap it didn't work. In just regular ggplot() it worked, I used geom_treemap I think it was. But in this data I have many 'labels' so i need the hover over to show the tooltip-data, so some plotly graph is needed - ggplot will not suffice.

I come across this section of code of directly generating a plotly-map w/o giving it a ggplot-object.

df_plotly <- plot_ly(
  df_konk_cum_tot,
  labels = ~ SNI2007,
  parents = NA,
  values = ~ sum_anstallda,
  type = 'treemap',
  hovertemplate = "Bransch: %{label}<br>Anställda: %{value}<extra></extra>") %>%
  layout(title = list(text = paste0('Anställda berörda av konkurser, kumulativt',
                                    '<br>',
                                    '<sup>',
                                    sprintf("%s - till och med ", geografi),'</sup>')),
 
         margin = list(l = 0, r = 0, b = 0, t = 70))


df_plotly

I don't know if this is some old function of plotly? It works, however the title gets centered, but I want it left-aligned - how do I pass an argument for this?

Also if there's a newer function I should use to create a plotly-treemap please advise.

Thanks!


Solution

  • You can control horizontal title alignment through x, xanchor & xref properties. Before playing around with those, it may be worth going through descriptions first - https://plotly.com/r/reference/layout/#layout-title-text

    Title layout is not specific to Plotly chart type, so here's just general example from ?plot_ly :

    library(plotly)
    plot_ly(z = ~volcano) |> 
      layout(title = list(text = "Maunga Whau Volcano",
                          x = 0,            # x position with respect to `xref` in normalized 
                                            # coordinates from "0" (left) to "1" (right).
                          xanchor ="left",  # horizontal alignment with respect to its x position.
                                            # "left" means that the title starts at x
                          xref = "paper"))  # "paper" refers to the width of the plotting area
    

    Created on 2023-02-25 with reprex v2.0.2