Search code examples
rr-plotly

R plot_ly: How to add horizontal space in plot area?


I am using plot_ly in R to create a line chart. By default, the line runs right up to the left and right edges of the plot area. I would like to add some space here, as is done by default in ggplot. Does anyone know how to do this with plot_ly?

Reproducible example:

df <- data.frame(date = seq(as.Date('2021-01-01'), length=50, by='day'),
                 value = rnorm(50))

plot_ly(df, x=~date, y=~value) %>% 
  add_lines(color=I('black')) %>% 
  layout(title = 'plot_ly', plot_bgcolor = 'E9E9E9')

ggplot(df, aes(x=date, y=value)) +
  geom_line() +
  ggtitle('ggplot')

I would like to add the space shown below with red arrows:


Solution

  • You can set the range in xaxis :

    library(plotly)
    
    plot_ly(df, x=~date, y=~value) %>% 
      add_lines(color=I('black')) %>% 
      layout(title = 'plot_ly', plot_bgcolor = 'E9E9E9', 
             xaxis = list(range = c(min(df$date) - 3, max(df$date) + 3)))
    

    enter image description here