3

I am trying to add a horizontal line at y=1 and a vertical line at x=1 to my contour plot, how do I do this?

My code looks the following way:

library(plotly)
library("mvtnorm")

cov=matrix(c(2,1,1,2),2,2)

x1=seq(-4,4,by=0.1)
x2=seq(-4,4,by=0.1)

d<-expand.grid(x1,x2)

z=dmvnorm(as.matrix(d),sigma=cov)

plot_ly(x=d[,1],y=d[,2],z=z,type="contour")
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
Ku-trala
  • 651
  • 3
  • 9
  • 20

2 Answers2

2

You could use

plot_ly(x = d[, 1], y = d[, 2], z = ~z, type = "contour") %>%
  add_segments(x = 1, xend = 1, y = -4, yend = 4, inherit = FALSE) %>%
  add_segments(x = -4, xend = 4, y = 1, yend = 1, inherit = FALSE) %>%
  layout(xaxis = list(range = c(-4, 4)),
         yaxis = list(range = c(-4, 4)))

enter image description here

where I added inherit = FALSE to avoid warnings, and the layout part to fix the x-axis.

Julius Vainora
  • 47,421
  • 9
  • 90
  • 102
1

There are two possibility for this.

The first one is with add_segments the other one is with layout:

  1. with add_segments

    plot_ly(x=d[,1],y=d[,2],z=z,type="contour")%>%
        add_segments(x = 0, xend = 0, y = -4, yend = 4)%>%
        add_segments(x = -4, xend = 4, y = 0, yend = 0)
    
  2. with layout:

    plot_ly(x=d[,1],y=d[,2],z=z,type="contour")%>%
        layout(shapes=list(type="line", x0=0, x1=0, y0=-4, y1=4))%>%
        layout(shapes=list(type="line", x0=-4, x1=4, y0=0, y1=0))%>
    

for changing colours or something similar i recommend the documentation of plot.ly

Keyur Potdar
  • 7,158
  • 6
  • 25
  • 40
mischva11
  • 2,811
  • 3
  • 18
  • 34