【问题标题】:Display maximum and minimum values of data points in Boxplot in plotly R在 plotly R 中显示 Boxplot 中数据点的最大值和最小值
【发布时间】:2021-08-18 04:06:44
【问题描述】:

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

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

【问题讨论】:

    标签: r boxplot r-plotly


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

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

    【讨论】:

    • 当我将鼠标悬停在箱线图上时,无论如何都会显示这些值,但我想将数据点的最小值和最大值显示为文本,而不需要将鼠标悬停在图上。我该怎么做?
    • 我扩充了答案:(类似于 ggplot)您将annotation(或add_text() 跟踪)添加到“静态”文本的情节图中。希望这能让你到达那里。
    猜你喜欢
    • 2021-04-04
    • 2013-06-05
    • 2015-03-26
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-27
    • 1970-01-01
    相关资源
    最近更新 更多