Home > Software design >  How to add vertical line between 2 markers in R plotly?
How to add vertical line between 2 markers in R plotly?

Time:09-09

I just started using plotly in R, and I've made a plot like this enter image description here with a syntax like this:

      maximum <- rnorm(30, mean = 20)
  datasource <- rnorm(30, mean = 15)
  minimum <- rnorm(30, mean = 10)
  x <- c(1:30)
  
  data <- data.frame(x,datasource,maximum,minimum)
  
  fig <- plot_ly(data, x = ~x, y = ~datasource, name = 'trace 1', type = 'scatter', mode = 'lines markers', marker = list(size = 10))
  fig <- fig %>% add_trace(y = ~maximum, name = 'maximum', mode = 'markers', marker = list(size = 10))
  
  fig <- fig %>% add_trace(y = ~minimum, name = 'minimum', mode = 'markers', marker = list(size = 10)) 
  
  fig <- fig %>% layout(title = "XBAR CHART",
                        xaxis = list(title = "ID"),
                        yaxis = list (title = "Measurement Value (mm)"))
  fig

I want to add a line connecting the minimum and maximum markers like the following. enter image description here

I've been trying but haven't found the solution.

I hope I find a solution here. thanks

CodePudding user response:

calculate the points that defined the lines

v_lines <-  mutate(rowwise(data),
                   vline=list(list(type="line",
                                   x0=x,
                                   x1=x,
                                   y0=minimum,
                                   y1=maximum,
                                   line=list(color="blue")))) |> pull(vline)

add them to the layout

fig <- fig %>% layout(title = "XBAR CHART",
                      shapes= v_lines,
                      xaxis = list(title = "ID"),
                      yaxis = list (title = "Measurement Value (mm)"))

CodePudding user response:

Like this?

ggplot(data=data, aes(x,datasource)) 
  geom_segment(data = data, aes(x = x, y = minimum, xend = x, yend = maximum), color = "light blue", size = 1) 
  geom_line(data = data, aes(x = x, y = datasource), color= "blue", size = 1) 
  geom_point(data=data, aes(x, minimum), color = "green", size=3) 
  geom_point(data=data, aes(x, maximum), color = "orange", size=3) 
  geom_point(color = "blue", size=3) 
  xlab("X - axis text") ylab("Y - axis text") 
  theme_light(base_size = 18, base_rect_size = 1) 
  • Related