4

I have an histogram like the one below and I want to plot a vertical line of a specific value on top of the histogram.

My code for the histogram is:

library(plotly)
p <- plot_ly(x = ~rnorm(50,mean = 50,sd = 10), type = "histogram")
p

I want to overlay a line on top of the histogram, for example say,

x <- 42

enter image description here

Can anyone help getting this?

radhikesh93
  • 870
  • 9
  • 25
krish
  • 1,388
  • 2
  • 18
  • 28

1 Answers1

4
library(plotly)
set.seed(1)
p <- plot_ly(x = ~rnorm(50,mean = 50,sd = 10), type = "histogram") %>%
  add_segments(x=42, y=0, xend=42, yend=14, line=list(color="red", width = 4))
p

A different solution (see here for details):

vline <- function(x = 0, color = "red") {
  list(
    type = "line", 
    y0 = 0, 
    y1 = 1, 
    yref = "paper",
    x0 = x, 
    x1 = x, 
    line = list(color = color)
  )
}
p <- plot_ly(x = ~rnorm(50, mean = 50,sd = 10), type = "histogram") %>%
  layout(shapes = list(vline(42)))
p

enter image description here

Marco Sandri
  • 23,289
  • 7
  • 54
  • 58