我需要生成一组直方图,其中有一条垂直线,在某些情况下远离直方图的值,有点像这样:
hist(mtcars$mpg, breaks = 15, xlim=c(0,160))
abline(v=150, lwd=2, lty=2, col="blue")
在 base R 中,如果我扩展 x 轴并添加垂直线,直方图本身不会改变。
理想情况下,我会使用 ggplot 而不是 base R 来绘制绘图,但是如果我这样做,在添加垂直线时直方图本身会发生变化:
ggplot(data = mtcars, aes(x=mpg))+
geom_vline(xintercept = 150, color= "blue", linetype="dashed")+
scale_x_continuous(c(0,160))+
geom_histogram(binwidth = 15, color="black", fill="white")
(第一个直方图是基于 R 的,第二个是 ggplot)
如何在 ggplot 中生成与 base R 中相同的直方图,带有垂直线?
但它真的改变了吗?
library(ggplot2)
library(patchwork)
p1 <- ggplot(data = mtcars, aes(x=mpg))+
scale_x_continuous(c(0,160))+
geom_histogram(binwidth = 15, color="black", fill="white") +
ggtitle("just the histogram")
p2 <- ggplot(data = mtcars, aes(x=mpg))+
scale_x_continuous(c(0,160))+
geom_histogram(binwidth = 15, color="black", fill="white") +
geom_vline(xintercept = 150, color= "blue", linetype="dashed") +
ggtitle("with vline")
p1 + p2
创建于 2023-04-22 与 reprex v2.0.2
我不太确定你期望“不改变”是什么。也许您希望 ggplot 看起来像 base R:在这种情况下,您的问题将重复为:R - 使用 ggplot2 模拟 hist() 的默认行为以获取 bin 宽度
这是与 ggplot2 完全相同的图。主要任务是设置正确的 binwidth 和 breaks:
library(ggplot2)
ggplot(mtcars, aes(x = mpg)) +
geom_histogram(binwidth = 2, color = "black", fill = "grey80", breaks = seq(0, 160, by = 2)) +
geom_vline(xintercept = 150, linetype = "dashed", color = "blue", size = 1) +
scale_x_continuous(limits = c(-10, 160), expand = c(0, 0)) +
scale_y_continuous(limits = c(0, 7.5), expand = c(0, 0)) +
theme_classic()