本文介绍了Plotly:如何在箱线图上添加中线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在箱形图上添加一条中线.

I would like to add trace of a median line on my box plot.

喜欢这个

到目前为止,这是我的情节:

Here are my plots so far:

library(plotly)
p <- plot_ly(y = ~rnorm(50), type = "box") %>%
  add_trace(y = ~rnorm(50, 1))

p

推荐答案

刚开始使用散点图 plot_ly(..., type='scatter', mode='lines', ...),并跟进每个箱形图一个 add_boxplot(...' inherit=FALSE, ...).以下是对整个 data.frame 执行此操作的方法:

Just start out with a scatter plot using plot_ly(..., type='scatter', mode='lines', ...), and follow up with one add_boxplot(...' inherit=FALSE, ...) per box plot. Here's how you do it for an entire data.frame:

带有示例数据的完整代码:

library(dplyr)
library(plotly)

# data
df <- data.frame(iris) %>% select(-c('Species'))
medians <- apply(df,2,median)

# create common x-axis values for median line and boxplots
xVals <- seq(0, length(medians)-1, by=1)

# plotly median line setup
p <- plot_ly(x = xVals, y=medians, type='scatter', mode='lines', name='medians')

# add a trace per box plot
i <- 0
for(col in names(df)){
  p <- p %>% add_boxplot(y = df[[col]], inherit = FALSE, name = col)
  i <- i + 1
}

# manage layout
p <- p %>% layout(xaxis = list(range = c(min(xVals)-1, max(xVals)+1)))
p

这篇关于Plotly:如何在箱线图上添加中线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-26 10:51