Search code examples
rplotlyscatter-plot

R plotly scatter marker plot distance ticks and axes


How come the distance between the ticks and axes is so huge? Moreover why doenst this chart start at 0?

library(plotly)

# Sample data
df <- data.frame(
  x = c(0, 1, 2, 3, 4, 5),
  y = c(0, 10, 14, 18, 24, 30)
)

# Create a scatter plot with markers
fig <- plot_ly(df, x = ~x, y = ~y, type = 'scatter', mode = 'markers',
               marker = list(size = 10, color = 'blue'), 
               text = ~paste('Point ', seq_along(x)))

# Show the plot
fig

enter image description here


Solution

  • We could change this with the layout() function:

    plot_ly(df, x = ~x, y = ~y, type = 'scatter', mode = 'markers',
                   marker = list(size = 10, color = 'blue'), 
                   text = ~paste('Point ', seq_along(x))) %>%
      layout(
      xaxis = list(range = c(0, max(df$x))),
      yaxis = list(range = c(0, max(df$y))),
      margin = list(l = 10, r = 10, b = 10, t = 10, pad = 4)
    )
    

    enter image description here