Make plotly always show the origin (0,0) when making the plot in R

Viewed 4606

I have a shiny application which present a scatterplot. The shiny user perform data filtering, then the data is display in the plotly graph. Sometime, the data created will be all negative or all positive, but I still want to plot to be positioned a way that the origin (0,0) is displayed.

Example:

dd <- data.frame(x=c(2,3,6,2), y=c(5,2,7,3))
plot_ly(data=dd, x=~x, y=~y, type="scatter", mode="markers")

gives:

enter image description here

But I want it to look initially more like that:

enter image description here

Any idea how to do that?

2 Answers

Use rangemode:

plot_ly(data=dd, x=~x, y=~y, type="scatter", mode="markers") %>%
  layout(
    xaxis = list(rangemode = "tozero"), 
    yaxis = list(rangemode = "tozero"))

enter image description here

This will also work with dd2 <- -1 * dd:

plot_ly(data=dd2, x=~x, y=~y, type="scatter", mode="markers") %>%
  layout(
    xaxis = list(rangemode = "tozero"), 
    yaxis = list(rangemode = "tozero"))

enter image description here

One can modify the axes ranges in layout like this:

plot_ly(data=dd, x=~x, y=~y, type="scatter", mode="markers") %>%
  layout(
      xaxis = list(range = c(~min(c(-1,x)), ~max(c(1,x)))),
      yaxis = list(range = c(~min(c(-1,y)), ~max(c(1,y)))))

enter image description here

Related