我使用虹膜数据集,目的是获取4个相邻的盒子图,并使它们共享一个从0到8的y轴。
par(mfrow=c(1,4))
boxplot(iris$Sepal.Length, width = 3)
boxplot(iris$Sepal.Width, width = 3)
boxplot(iris$Petal.Length, width = 3)
boxplot(iris$Petal.Width, width = 3)我现在有四个情节在一起,但他们都有自己的y轴,适合他们自己的最小和最大。
我怎么能让他们共用y轴?我还想要一个x轴,在这里我可以给它们贴上"Sepal.Length“、"Sepal.Width”等标签。
解决方案,如果可能的话,不要用ggplot,谢谢。
发布于 2021-06-14 15:05:19
三种选择:
基本图形
在绘图之前确定y的范围。为此,可以从下面的ylim=之一中选择两个选项:
### if you have no outliers or will not plot them
ylim <- range(boxplot.stats(as.matrix(iris[,-5]))$stats)
### if you have outliers and/or want to leave room for them, then
ylim <- range(as.matrix(iris[,-5]))在这种情况下,总体范围不会改变,尽管Sepal.Width在图中确实包含一些异常值。
从这里开始,用ylim=ylim绘制它们
par(mfrow = c(1, 4))
boxplot(iris$Sepal.Length, width = 3, ylim = ylim)
boxplot(iris$Sepal.Width, width = 3, ylim = ylim)
boxplot(iris$Petal.Length, width = 3, ylim = ylim)
boxplot(iris$Petal.Width, width = 3, ylim = ylim)

基本图形,取2
重组后,将它们分组。
irislong <- reshape2::melt(iris, "Species", variable.name = "Var")
head(irislong)
# Species Var value
# 1 setosa Sepal.Length 5.1
# 2 setosa Sepal.Length 4.9
# 3 setosa Sepal.Length 4.7
# 4 setosa Sepal.Length 4.6
# 5 setosa Sepal.Length 5.0
# 6 setosa Sepal.Length 5.4
boxplot(value ~ Var, data = irislong)

(还有一种情况是使用tidyr::pivot_longer对其进行整形,我在下面的ggplot2部分中演示了这一点。)
ggplot2
(即使您要求提供非ggplot2 2,因为它有时提供更多的权力,而且有些人认为它看起来更好,当然是主观的。)
ggplot(tidyr::pivot_longer(iris, -Species), aes(value)) +
geom_boxplot() +
facet_grid(name ~ .)

如果你喜欢的方向和基本的方向一样,那么
ggplot(tidyr::pivot_longer(iris, -Species), aes(value)) +
geom_boxplot() +
facet_grid(. ~ name) +
coord_flip()

通常,使用公式方法(在第二个基本图形图中)或faceting (在ggplot2中)允许将盒图分组为多个变量。
https://stackoverflow.com/questions/67972090
复制相似问题