在plotly R的箱线图中显示数据点的最大值和最小值

在plotly R的箱线图中显示数据点的最大值和最小值,r,boxplot,r-plotly,R,Boxplot,R Plotly,如何将最小和最大数据点的值显示为在R中使用plotly绘制的箱线图中的文本?以下是代码的示例参考: plot_ly(x = ~rnorm(50), type = "box") %>% add_trace(x = ~rnorm(50, 1)) 在绘制水平箱线图时,必须“切换”箱线图的方向(最小、最大、中值、q1、q3) plot_ly(x = ~rnorm(50), type = "box" #-------------- set direction

如何将最小和最大数据点的值显示为在R中使用plotly绘制的箱线图中的文本?以下是代码的示例参考:

plot_ly(x = ~rnorm(50), type = "box") %>% add_trace(x = ~rnorm(50, 1))
在绘制水平箱线图时,必须“切换”箱线图的方向(最小、最大、中值、q1、q3)

plot_ly(x = ~rnorm(50), type = "box"
#-------------- set direction / switch on     
         , hoverinfo = "x") %>%    # let plotly know that x-direction give the hoverinfo
#----------------------------------------
   add_trace(x = ~rnorm(50, 1)) %>% 

#---------------- format label - here show only 2 digits
  layout(xaxis = list(hoverformat = ".2f"))  # again define for x-axis/direction!
基于评论的修改:添加注释

Plotly支持将文本添加为跟踪(即
add_text()
)或布局选项(即
annotations=list(…)
)。
注释选项提供对偏移、指针箭头等的支持。
因此,我选择了这个选项

为了能够访问最小值和最大值,我拉出了向量数据定义。标签将术语
min
max
与两位四舍五入值组合在一起。根据你的喜好进行调整,可能在情节之外。您可以定义提供给
annotation=list(…)
调用选项的向量。只需注意向量中元素的顺序

set.seed(1234)
x1 <- rnorm(50)
x2 <- rnorm(50, 1)

plot_ly(type = 'box', hoverinfo = "x") %>%
    add_trace(x = x1) %>%
    add_trace(x = x2) %>%
    layout(title = 'Box Plot',
           annotations = list(
           #------------- (x,y)-position vectors for the text annotation
               y = c(0,1),   # horizontal boxplots, thus 0:= trace1 and 1:= trace2
               x = c( min(x1), min(x2)   # first 2 elements reflect minimum values
                     ,max(x1), max(x2)   # ditto for maximum values
                     ),
           #------------- text label vector - simple paste of label & value
               text = c( paste0("min: ", round(min(x1),2)), paste0("min: ", round(min(x2),2)) 
                        ,paste0("max: ", round(max(x1),2)), paste0("max: ", round(max(x2),2)) 
                        ),
           #-------------- you can use a pointer arrow
               showarrow = TRUE
           #-------------- there are other placement options, check documentation for this
           )
    )
set.seed(1234)
x1%
添加_道(x=x2)%>%
布局(标题=‘方框图’,
注释=列表(
#-------------(x,y)-文本注释的位置向量
y=c(0,1),#水平箱线图,因此0:=trace1和1:=trace2
x=c(最小值(x1),最小值(x2)#前两个元素反映最小值
,max(x1),max(x2)#最大值同上
),
#-------------文本标签向量-标签和值的简单粘贴
text=c(粘贴0(“最小:”,圆形(最小(x1),2)),粘贴0(“最小:”,圆形(最小(x2),2))
,粘贴0(“最大:”,圆形(最大(x1),2)),粘贴0(“最大:”,圆形(最大(x2),2))
),
#--------------您可以使用指针箭头
showarrow=TRUE
#--------------还有其他放置选项,请查看文档以了解此选项
)
)

当我将鼠标悬停在箱线图上时,值仍会显示,但我希望将数据点的最小值和最大值显示为文本,而无需将鼠标悬停在图上。我该怎么做呢?我补充了答案:(类似于ggplot)您将
注释
(或
添加_text()
跟踪)添加到“静态”文本的绘图中。希望这能让你达到目的。