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")
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)))

where I added inherit = FALSE to avoid warnings, and the layout part to fix the x-axis.
There are two possibility for this.
The first one is with add_segments the other one is with layout:
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With