1

Using r, I'm trying to find (1) How do I add gridlines to this contour plot example using the Plot_ly function in r? (2) How do I control the number of tick intervals between gridlines?

x1 <- -10:10
y1 <- -10:10
z1 <- sqrt(outer(x1 ^ 2, y1 ^ 2, "+"))
fig <- plot_ly(z = z1, x = x1, y = y1,  type = "contour", 
                line = list(width = 1.5, color = "black"),
               contours = list(showlabels = TRUE))
fig

contour plot example

Erez
  • 21
  • 3
  • You can use [Plotly's reference sheet](https://plotly.com/r/reference/contour). When you say gridlines, are you referring to the contour lines or the actual cartesian grid? You can change the number of contours with `ncontour` (When I plotted this, `ncontour` seems to have defaulted around 20.) – Kat Sep 16 '22 at 23:48
  • Yes, I mean the Cartesian Grid. Let's say in this simple example, I want to add x and y grids every 1 unit. I also want the grid to be non-intrusive, i.e., to control its color and form. Thanks so much. – Erez Sep 18 '22 at 09:41
  • [This answer](https://stackoverflow.com/a/71346824/17303805) shows how to specify gridlines for a 3D contour plot, and may be relevant. – zephryl Sep 20 '22 at 12:58

2 Answers2

2

Plotly is always going to put the traces on top of the grid lines, so it doesn't matter what you do with the grid lines when the entire plot is filled in.

Alternatively, you can use shapes to mimic grid lines.

Here is an example with simulated gridlines for the y-axis.

hlines <- function(y = 0, color = "white") {
  list(type = "line",
       x0 = 0, x1 = 1, xref = "paper", y0 = y, y1 = y, 
       line = list(color = color, width = 1))
}
fig$x$layout$shapes <- lapply(-10:10, hlines)
fig

enter image description here

Kat
  • 15,669
  • 3
  • 18
  • 51
  • Thanks for all your help! Much appreciated. I'll post below the full answer based on your help. – Erez Sep 20 '22 at 12:45
1

Thank you all for your help. Much appreciated. Below I document the full answer.

contour plot example with cartesian grid lines

rm(list=ls(all=TRUE))
library(plotly)
x1 <- -10:10
y1 <- -10:10
z1 <- sqrt(outer(x1 ^ 2, y1 ^ 2, "+"))
fig <- plot_ly(z = z1, x = x1, y = y1,  type = "contour", 
               line = list(width = 1.5, color = "black"),
               contours = list(showlabels = TRUE))
fig

# adding cartesian horizontal grid lines

hlines <- function(y = 0, color = "white") {
  list(type = "line",
       x0 = 0, x1 = 1, xref = "paper", y0 = y, y1 = y, 
       line = list(color = color, width = 0.5))
}
fig$x$layout$shapes <- lapply(-10:10, hlines)
fig


#Add vertical lines
vlines <- function(x = 0, color = "white") {
  list(type = "line",
       y0 = 0, y1 = 1, yref = "paper", x0 = x, x1 = x,
       line = list(color = color, width = 0.5))
}

fig$x$layout$shapes[22:42] <- lapply(-10:10, vlines)
fig

enter image description here

Erez
  • 21
  • 3