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

问题描述

我想在箱形图中添加一条中线的痕迹.

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

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

08-29 03:52