简体   繁体   English

使用Plotly在R中的直方图上覆盖垂直线

[英]Overlay vertical line on top of histogram in R using Plotly

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

在此处输入图片说明

Can anyone help getting this? 有人可以帮忙吗?

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

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM