r - ggplot 中的直方图在 X 轴上不是从零开始

标签 r ggplot2 histogram

<分区>

所以,这是第一次使用 ggplot 制作直方图,我看到的是,对于我的数据,导出的直方图如下所示。

enter image description here

我不喜欢的是,第一个 bin 不包含零,它从大约 5 或 6 开始。有人遇到过这样的事情吗?

我使用了一系列 binwidths,从 1 到 20,它一直在这样做。

数据:

structure(list(V1 = c(8, 4.4, 9.4, 29.4, 135.6, 65, 70.9, 15.2, 38.8, 87.2, 5.2, 0.2, 7.8, 46.4, 35.9, 77.4, 34.2, 157.4, 46.4, 19, 43.8, 41.2, 96.8, 25.6, 40.2, 111.8, 111.8, 49.8, 39.4, 9.6, 11.6, 8.6, 44.2, 41, 4.6, 36.2, 12.4, 45.8, 0, 30.8, 134.6, 167.2, 13.8, 56.6, 112.3, 13.6, 18.8, 18.2, 7, 40.4, 30.8, 130.2, 234.6, 106.2, 87.2, 15, 7.6, 63, 18, 2.6, 28, 24, 153.2, 24.4, 69.6, 27, 134, 181.6, 46, 85.4, 18.6, 32, 83.6, 42.6, 32.8, 127.5, 92.8, 122, 129.6, 35.4, 20.6, 88, 14.8, 12.8, 33.8, 58.6, 104.2, 0.2)), class = "data.frame", row.names = c(NA, -88L))

代码:

library(ggplot2)
library(scales)
dat = read.csv('mo.csv')
p2=ggplot(dat, aes(x = dat$v2)) +
  geom_histogram(color="black", fill="grey40", bins=25)+ 
  scale_x_continuous(breaks = seq(0, 255, 25), limits = c(0,255), expand=c(0,0))+
  scale_y_continuous(expand = c(0,0),limits = c(0,16.5), breaks = pretty(dat$v2, n = 140))
p2

最佳答案

ggplot(dat, aes(x = dat$V1)) +
  geom_histogram(color="black", fill="grey40", bins=20)+
  scale_x_continuous(breaks = seq(0,250,25))+
  scale_y_continuous(expand = c(0,0),limits = c(0,16.5), breaks = pretty(dat$V1, n = 140))

这似乎是您要找的。虽然 25 个箱子看起来比 20 个好得多,但我是。

关于r - ggplot 中的直方图在 X 轴上不是从零开始,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53565242/

相关文章:

r - 从.Xdf文件中删除重复的记录

r - R中的 'rexp(1000, 1)'和 'replicate(1000, rexp(1,1))'有什么区别?

linux - 如何安装 Fortran 编译器 (gcc42-fortran)

r - ggplot2 以错误的顺序放置数据标签(geom_text)

r - ggplot2 - boxplot 多个 data.frames 同时保持秩序

r - 如何在ggplot中添加带有标签的水平虚线

json - 使用 jq 生成字段值频率计数

r - 尽管 echo=FALSE,knitr set_parent() 始终输出 NULL

r - 在 R 中使用 ggplot2 修改图例

matlab - 将曲线拟合到直方图