繁体   English   中英

在 plotly R 中的 Boxplot 中显示数据点的最大值和最小值

[英]Display maximum and minimum values of data points in Boxplot in plotly R

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

plot_ly(x = ~rnorm(50), type = "box") %>% add_trace(x = ~rnorm(50, 1))

您必须“切换”箱线图的方向(最小值、最大值、中值、q1、q3),就像 plot 水平箱线图一样。

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(...) )。
注释选项提供对偏移量、指针箭头等的支持。
因此,我选择了这个选项。

为了能够访问最小值和最大值,我提取了矢量数据定义。 标签将术语minmax与 2 位四舍五入的值结合在一起。 根据您的喜好调整它,并可能在 plot 之外。 您可以定义提供给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
           )
    )

在此处输入图像描述

暂无
暂无

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

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