[英]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(...)
)。
注釋選項提供對偏移量、指針箭頭等的支持。
因此,我選擇了這個選項。
為了能夠訪問最小值和最大值,我提取了矢量數據定義。 標簽將術語min
和max
與 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.