[英]Frequency Distribution Histogram with Bins with Two Variables on the Y-axis in R
[英]Frequency count histogram displaying only integer values on the y-axis?
我非常感谢任何人帮助解决这个问题。 看起来应该很简单,但经过几个小时的试验,我不得不停下来寻求帮助。 非常感谢您!
如何确保在 ggplot2 中,直方图的 y 轴仅使用整数(频率计数值)而不是小数进行标记?
geom_histogram()
, geom_bar()
和geom(col)
- 在每种情况下,包括或不包括相关的参数stat = "identity"
。+ scale_y_discrete()
,有或没有+ scale_x_discrete()
理想情况下,解决方案将使用 baseR 或 ggplot2,而不是额外的外部依赖项,例如使用 function pretty_breaks()
函数在 ZEFE90A8E604A7C840E88D03A6ZF6 或类似的scales
中。
sample <- data.frame(binMidPts = c(4500,5500,6500,7500), counts = c(8,0,9,3))
x 轴由连续变量的 bin 组成,y 轴旨在显示这些 bin 中的观察计数。 例如,Bin 1 覆盖 x 轴范围 [4000 <= x < 5000],具有中点 4500,在该 bin / 范围内观察到 8 个数据点。
下面的代码生成一个类似于我正在寻找的图形,但是 y 轴在中断处标有十进制值(这是无效的,因为数据是 integer 计数值)。
ggplot(data = sample, aes (x = binMidPts, y = counts)) + geom_col()
我意识到我可以将中断/标签硬编码到scale_y_continuous()
轴上,但是(a)我更喜欢灵活的解决方案来应用于许多不同大小的数据集,其中比例事先不知道,并且(b)我期望必须有一种更简单的方法来生成基本的直方图。
I've consulted many Stack Overflow questions, the ggplot2 manual ( https://ggplot2.tidyverse.org/reference/scale_discrete.html ), the sthda.com examples and various blogs. 这些倾向于解决相关问题,例如使用scale_y_continuous
,或者在底层数据集中没有可用的计数数据,因此依赖 stat_bin() 进行转换。
任何帮助将非常感激。 谢谢你。
该线程的未来读者可能会发现了解由 base::pretty() 形成的中断值范围不一定会扩展到零是有帮助的。 因此,轴刻度可能会省略介于零和中断下限之间的值,如下所示:
为了解决这个问题,我在 range() 参数中包含了“0”,即:
ggplot(data = sample, aes (x = binMidPts, y = counts)) + geom_col() +
scale_y_continuous(breaks=round(pretty(range(0,sample$counts))))
它在 y 轴上给出了所需的满量程,因此:
怎么样:
ggplot(data = sample, aes (x = binMidPts, y = counts)) + geom_col() +
scale_y_continuous( breaks=round(pretty( range(sample$counts) )) )
这个答案从pretty_breaks
的尺度上建议了 pretty_breaks。 pretty_breaks的手册页从base中提到了pretty 。 从那里你只需要将它四舍五入到最近的 integer。
或者您可以使用针对您正在使用的数据集自定义的一些规则来计算中断,如下所示
library(ggplot2)
breaks_min <- 0
breaks_max <- max(sample[["counts"]])
# Assume 5 breaks is perferable
breaks_bin <- round((breaks_max - breaks_min) / 5)
custom_breaks <- seq(breaks_min, breaks_max, breaks_bin)
ggplot(data = sample, aes (x = binMidPts, y = counts)) +
geom_col() +
scale_y_continuous(breaks = custom_breaks, expand = c(0, 0))
由代表 package (v2.0.0) 于 2021 年 4 月 28 日创建
默认的 y 轴中断是使用scales::extended_breaks()
计算的。 这个 function 工厂有一个...
参数,它将 arguments 传递给labeling::extended
,它有一个Q
参数来表示它认为“好数字”。 如果您从默认值中省略2.5
,则当范围为 3 或更大时,您应该得到 integer 中断。
library(ggplot2)
library(scales)
sample <- data.frame(binMidPts = c(4500,5500,6500,7500), counts = c(8,0,9,3))
ggplot(data = sample, aes (x = binMidPts, y = counts)) +
geom_col() +
scale_y_continuous(
breaks = extended_breaks(Q = c(1, 5, 2, 4, 3))
)
由代表 package (v1.0.0) 于 2021 年 4 月 28 日创建
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.