如何仅使用 barplot 函数调整 R 中条形图的 y 轴
How to adjust the y-axis of bar plot in R using only the barplot function
使用这个例子:
x<-mtcars;
barplot(x$mpg);
你会得到一个由 (0 - 30) 中的许多条形图组成的图表。
我的问题是如何调整它,使 y 轴为 (10-30),底部有一个裂口,表明有数据低于截止值?
具体来说,我想在基础 R 程序中仅使用 barplot
函数而不使用 plotrix 中的函数(与已经提供的建议不同)。这可能吗?
不推荐这样做。切掉条形图的底部通常被认为是不好的做法。但是,如果您查看 ?barplot
,它有一个 ylim
参数,它可以与 xpd = FALSE
(打开 "clipping")组合以切断条形图的底部。
barplot(mtcars$mpg, ylim = c(10, 30), xpd = FALSE)
另请注意,这里要小心。我按照你的问题使用了 0 和 30 作为 y-bounds,但最大 mpg 是 33.9,所以我也剪掉了值 > 30.
的 4 个条的顶部
我知道在轴上制作 "split" 的唯一方法是使用 plotrix
。所以,基于
Specifically, I want to do this in base R program using only the barplot function and not functions from plotrix (unlike the suggests already provided). Is this possible?
答案是 "no, this is not possible",我想你的意思是。 plotrix
当然可以,它使用基本的 R 函数,所以你可以按照他们的方式去做,但是你也可以使用 plotrix
.
您可以在条形图上绘制,也许水平虚线(如下所示)可以帮助表明您违反了条形图应该是什么的普遍接受的规则:
abline(h = 10.2, col = "white", lwd = 2, lty = 2)
生成的图片如下:
编辑: 您可以使用 segments
来欺骗轴中断,如下所示:
barplot(mtcars$mpg, ylim = c(10, 30), xpd = FALSE)
xbase = -1.5
xoff = 0.5
ybase = c(10.3, 10.7)
yoff = 0
segments(x0 = xbase - xoff, x1 = xbase + xoff,
y0 = ybase-yoff, y1 = ybase + yoff, xpd = T, lwd = 2)
abline(h = mean(ybase), lwd = 2, lty = 2, col = "white")
As-is,这很脆弱,xbase
是手动调整的,因为它取决于您的数据范围。您可以将条形图切换为 xaxs = "i"
并设置 xbase = 0
以获得更高的可预测性,但为什么不使用已经为您完成所有这些工作的 plotrix
呢?!
ggplot 在评论中你说你不喜欢 ggplot
的外观。这很容易定制,例如:
library(ggplot2)
ggplot(x, aes(y = mpg, x = id)) +
geom_bar(stat = "identity", color = "black", fill = "gray80", width = 0.8) +
theme_classic()
使用这个例子:
x<-mtcars;
barplot(x$mpg);
你会得到一个由 (0 - 30) 中的许多条形图组成的图表。
我的问题是如何调整它,使 y 轴为 (10-30),底部有一个裂口,表明有数据低于截止值?
具体来说,我想在基础 R 程序中仅使用 barplot
函数而不使用 plotrix 中的函数(与已经提供的建议不同)。这可能吗?
不推荐这样做。切掉条形图的底部通常被认为是不好的做法。但是,如果您查看 ?barplot
,它有一个 ylim
参数,它可以与 xpd = FALSE
(打开 "clipping")组合以切断条形图的底部。
barplot(mtcars$mpg, ylim = c(10, 30), xpd = FALSE)
另请注意,这里要小心。我按照你的问题使用了 0 和 30 作为 y-bounds,但最大 mpg 是 33.9,所以我也剪掉了值 > 30.
的 4 个条的顶部我知道在轴上制作 "split" 的唯一方法是使用 plotrix
。所以,基于
Specifically, I want to do this in base R program using only the barplot function and not functions from plotrix (unlike the suggests already provided). Is this possible?
答案是 "no, this is not possible",我想你的意思是。 plotrix
当然可以,它使用基本的 R 函数,所以你可以按照他们的方式去做,但是你也可以使用 plotrix
.
您可以在条形图上绘制,也许水平虚线(如下所示)可以帮助表明您违反了条形图应该是什么的普遍接受的规则:
abline(h = 10.2, col = "white", lwd = 2, lty = 2)
生成的图片如下:
编辑: 您可以使用 segments
来欺骗轴中断,如下所示:
barplot(mtcars$mpg, ylim = c(10, 30), xpd = FALSE)
xbase = -1.5
xoff = 0.5
ybase = c(10.3, 10.7)
yoff = 0
segments(x0 = xbase - xoff, x1 = xbase + xoff,
y0 = ybase-yoff, y1 = ybase + yoff, xpd = T, lwd = 2)
abline(h = mean(ybase), lwd = 2, lty = 2, col = "white")
As-is,这很脆弱,xbase
是手动调整的,因为它取决于您的数据范围。您可以将条形图切换为 xaxs = "i"
并设置 xbase = 0
以获得更高的可预测性,但为什么不使用已经为您完成所有这些工作的 plotrix
呢?!
ggplot 在评论中你说你不喜欢 ggplot
的外观。这很容易定制,例如:
library(ggplot2)
ggplot(x, aes(y = mpg, x = id)) +
geom_bar(stat = "identity", color = "black", fill = "gray80", width = 0.8) +
theme_classic()