【发布时间】:2021-08-18 04:06:44
【问题描述】:
如何在 R 中使用 plotly 绘制的箱线图中将最小和最大数据点的值显示为文本?以下是代码的示例参考:
plot_ly(x = ~rnorm(50), type = "box") %>% add_trace(x = ~rnorm(50, 1))
【问题讨论】:
如何在 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 与一个 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
)
)
【讨论】:
annotation(或add_text() 跟踪)添加到“静态”文本的情节图中。希望这能让你到达那里。