Search code examples
rplotplotlydata-visualization

R: Automatically Forcing Titles To Become Horizontal


I am working with the R programming language.

I am following this tutorial (https://plotly.com/r/bar-charts/) and made the following graph:

library(plotly)

Animals <- c("A Very Long Title That Probably Won't Fit", "A Very, Very Long Title That Probably Won't Fit ", "A Very, Very, Very Long Title That Probably Won't Fit")
SF_Zoo <- c(20, 14, 23)
LA_Zoo <- c(12, 18, 29)
data <- data.frame(Animals, SF_Zoo, LA_Zoo)

fig <- plot_ly(data, x = ~Animals, y = ~SF_Zoo, type = 'bar', name = 'SF Zoo')
fig <- fig %>% add_trace(y = ~LA_Zoo, name = 'LA Zoo')
fig <- fig %>% layout(yaxis = list(title = 'Count'), barmode = 'group')

When I view this graph, the titles are all "slanted diagonally":

enter image description here

I understand that if I increase the size of the screen, the titles are no longer slanted (the way I want):

enter image description here

**I was wondering if there is some option in R that can be used such that the titles will never slant diagonally and will always be horizontal (no matter what size the graph) ** - if there is no space, I would like the titles to "tile horizontally", for example:

A Very, Very 
Long Title That 
Probably Won't Fit

I plan on saving these graphs as an interactive html file using the htmltools/htmlwidets library, and I would like to prevent these titles from being diagonally slanted, and instead be horizontally tiled.

Is there some option in plotly/r that can be used to do this?

Thank You!


Solution

  • Maybe something like this?

    library(plotly)
    
    Animals <- c("A Very Long Title \n That Probably Won't Fit", "A Very, Very Long Title \n That Probably Won't Fit ", "A Very, Very, Very Long \n Title That Probably Won't Fit")
    SF_Zoo <- c(20, 14, 23)
    LA_Zoo <- c(12, 18, 29)
    data <- data.frame(Animals, SF_Zoo, LA_Zoo)
    
    fig <- plot_ly(data, x = ~Animals, y = ~SF_Zoo, type = 'bar', name = 'SF Zoo') %>% 
        add_trace(y = ~LA_Zoo, name = 'LA Zoo') %>% 
        layout(yaxis = list(title = 'Count'), barmode = 'group',
               xaxis = list(tickangle=0, tickfont = list(size=12)))
    fig
    

    enter image description here