Add multiple horizontal lines in a boxplot

做~自己de王妃 提交于 2019-12-07 10:31:14

问题


I know that I can add a horizontal line to a boxplot using a command like

abline(h=3)

When there are multiple boxplots in a single panel, can I add different horizontal lines for each single boxplot?

In the above plot, I would like to add lines 'y=1.2' for 1, 'y=1.5' for 2, and 'y=2.1' for 3.


回答1:


I am not sure that I understand exactly, what you want, but it might be this: add a line for each boxplot that covers the same x-axis range as the boxplot.

The width of the boxes is controlled by pars$boxwex which is set to 0.8 by default. This can be seen from the argument list of boxplot.default:

formals(boxplot.default)$pars
## list(boxwex = 0.8, staplewex = 0.5, outwex = 0.5)

So, the following produces a line segment for each boxplot:

# create sample data and box plot
set.seed(123)
datatest <- data.frame(a = rnorm(100, mean = 10, sd = 4),
                       b = rnorm(100, mean = 15, sd = 6),
                       c = rnorm(100, mean = 8, sd = 5))
boxplot(datatest)

# create data for segments
n <- ncol(datatest)
# width of each boxplot is 0.8
x0s <- 1:n - 0.4
x1s <- 1:n + 0.4
# these are the y-coordinates for the horizontal lines
# that you need to set to the desired values.
y0s <- c(11.3, 16.5, 10.7)

# add segments
segments(x0 = x0s, x1 = x1s, y0 = y0s, col = "red")

This gives the following plot:



来源:https://stackoverflow.com/questions/34366196/add-multiple-horizontal-lines-in-a-boxplot

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!