Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Contour plot adding lines [duplicate]

Tags:

r

plotly

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")
like image 299
Ku-trala Avatar asked Feb 04 '26 11:02

Ku-trala


2 Answers

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.

like image 172
Julius Vainora Avatar answered Feb 06 '26 04:02

Julius Vainora


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

like image 31
mischva11 Avatar answered Feb 06 '26 02:02

mischva11



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!