此问题已在此处有答案:
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为底的直方图相同的垂直线直方图?
2条答案
按热度按时间toiithl61#
下面是与ggplot2完全相同的图。主要任务是设置正确的binwidth和breaks:
kwvwclae2#
但它真的改变了吗?
创建于2023-04-22使用reprex v2.0.2
我不太清楚你期望“不改变”是什么。也许你希望ggplot看起来像base R:在这种情况下,您的问题将重复到:R - emulate the default behavior of hist() with ggplot2 for bin width