如何更改Plotly分位数计算方法及处理ggplotly分位数计算逻辑
我来帮你理清楚Plotly和ggplotly的分位数计算逻辑,以及怎么自定义这个计算方法——结合你给出的测试数据,咱们一步步来:
先搞懂ggplotly的分位数逻辑
其实ggplotly本质上是个“转换器”:当你用ggplot2画好图(比如箱线图),它会直接复用ggplot2已经计算好的所有统计值(包括分位数、中位数、箱线的上下限),完全不会重新计算分位数。也就是说,ggplotly的分位数逻辑100%继承自ggplot2的设置。
用你的测试数据来验证一下:
vec <- c(9.56630105983885, 9.2478753964443, 10.0860135756819, 8.61391863126551, 9.94710349615399, 7.14660035433632, 8.22017617694062, 10.0666294326466, 9.35484039252854, 12.5410005237513, 12.5687999720704, 9.91564647202826, 7.55332442693865, 11.2588496810078, 10.9914482049276, 11.9021198944421, 6.3190685543082, 9.22657465466812, 11.216871586139, 12.2549168985367 ) library(tidyverse) library(plotly) # 用ggplot2画箱线图 p_ggplot <- ggplot(data.frame(value = vec), aes(y = value)) + geom_boxplot() # 提取ggplot2计算的分位数、中位数、须的范围 ggplot_build(p_ggplot)$data[[1]] %>% select(y, ymin, lower, middle, upper, ymax)
运行这段代码,你会看到ggplot2默认用的是quantile(vec, type = 7)(这是base R quantile函数的默认类型,也是ggplot2箱线图的默认设置)。把这个图转成ggplotly后,所有数值都是直接复用的,不会变。
怎么改ggplotly的分位数计算?
既然ggplotly跟着ggplot2走,那改ggplot2的分位数设置就行。ggplot2的geom_boxplot可以通过quantile.type参数指定分位数计算类型,比如改成type=6(或者其他你需要的类型):
# 用type=6的分位数方法画箱线图 p_ggplot_custom <- ggplot(data.frame(value = vec), aes(y = value)) + geom_boxplot(quantile.type = 6) # 转成ggplotly,此时展示的就是自定义后的分位数结果 p_ggplotly_custom <- ggplotly(p_ggplot_custom)
这样就能轻松改变ggplotly里的分位数逻辑了。
直接改Plotly原生图的分位数计算
如果你不用ggplotly,直接用Plotly的原生函数(比如plot_ly)画图,默认的分位数计算可能和R的不一样。这时候就得自己先算好分位数,再手动传给Plotly:
# 先自定义计算分位数,比如用type=6 custom_quants <- quantile(vec, probs = c(0.25, 0.5, 0.75), type = 6) # 计算箱线须的范围(常用1.5倍IQR规则) iqr_val <- IQR(vec, type = 6) lower_whisker <- max(min(vec), custom_quants[1] - 1.5 * iqr_val) upper_whisker <- min(max(vec), custom_quants[3] + 1.5 * iqr_val) # 手动构建Plotly箱线图,传入自定义的统计值 p_plotly_custom <- plot_ly( y = vec, type = "box", q1 = custom_quants[1], median = custom_quants[2], q3 = custom_quants[3], lowerfence = lower_whisker, upperfence = upper_whisker, boxpoints = "all" # 显示所有原始数据点,方便对比 )
这样就完全摆脱了Plotly默认的分位数计算,用你指定的方法来生成箱线图。
验证不同分位数方法的差异
你可以直接对比不同type的计算结果,方便选到适合自己的:
# 对比type=2、6、7的分位数结果 data.frame( type_2 = quantile(vec, probs = c(0.25, 0.5, 0.75), type = 2), type_6 = quantile(vec, probs = c(0.25, 0.5, 0.75), type = 6), type_7 = quantile(vec, probs = c(0.25, 0.5, 0.75), type = 7) )
内容的提问来源于stack exchange,提问作者Vincent Guyader
相关产品推荐
相关产品推荐

