R语言 添加geom_vline时Ggplot mangles直方图[重复]

mmvthczy  于 2023-04-27  发布在  其他
关注(0)|答案(2)|浏览(111)

此问题已在此处有答案

R - emulate the default behavior of hist() with ggplot2 for bin width(1个答案)
2天前关闭。
我需要生成一组直方图,其中有一条垂直线,在某些情况下远离直方图的值,有点像这样:

hist(mtcars$mpg, breaks = 15, xlim=c(0,160))
abline(v=150, lwd=2, lty=2, col="blue")

在基数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中生成与以R为底的直方图相同的垂直线直方图?

toiithl6

toiithl61#

下面是与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()

kwvwclae

kwvwclae2#

但它真的改变了吗?

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 - emulate the default behavior of hist() with ggplot2 for bin width

相关问题