如何在R语言plotly绘制的箱线图中显示数据点最大最小值的文本标注?
R语言plotly箱线图添加最大最小值文本标注方法
实现思路很简单:先统计每个箱线分组的最大、最小值,再用add_annotations()接口把数值标注到对应位置即可。
完整可运行示例代码(基于你提供的示例改造)
library(plotly) # 固定随机种子,结果可复现 set.seed(123) # 生成和示例对应的两组测试数据 data1 <- rnorm(50) data2 <- rnorm(50, 1) # 提前计算每组的极值 min1 <- min(data1) max1 <- max(data1) min2 <- min(data2) max2 <- max(data2) # 绘图+标注 plot_ly() %>% # 绘制两组箱线 add_trace(x = ~data1, type = "box", name = "组1") %>% add_trace(x = ~data2, type = "box", name = "组2") %>% # 标注组1最小值 add_annotations( x = min1, y = 0, text = paste0("min: ", round(min1, 2)), xanchor = "right", showarrow = TRUE, arrowhead = 1 ) %>% # 标注组1最大值 add_annotations( x = max1, y = 0, text = paste0("max: ", round(max1, 2)), xanchor = "left", showarrow = TRUE, arrowhead = 1 ) %>% # 标注组2最小值 add_annotations( x = min2, y = 1, text = paste0("min: ", round(min2, 2)), xanchor = "right", showarrow = TRUE, arrowhead = 1 ) %>% # 标注组2最大值 add_annotations( x = max2, y = 1, text = paste0("max: ", round(max2, 2)), xanchor = "left", showarrow = TRUE, arrowhead = 1 )
参数说明
- 水平箱线的分组y坐标默认从0开始按顺序递增,如果你用的是垂直箱线,把坐标逻辑反过来即可:x填分组名,y填极值,用
yanchor控制文本位置避免重叠 round()用来控制显示的小数位数,可按需调整- 不需要箭头指向极值点的话,把
showarrow设为FALSE即可
内容的提问来源于stack exchange,提问作者hk2
相关产品推荐
相关产品推荐

