用不同 y-scales 叠加直方图
Overlaying histogram with different y-scales
我正在努力解决以下问题:
我想绘制两个直方图,但由于两个 类 之一的统计数据比另一个少得多,我需要添加第二个 y-axis 以便直接比较值。
我在下面报告我目前使用的代码和结果。
提前致谢!
ggplot(data,aes(x= x ,group=class,fill=class)) + geom_histogram(position="identity",
alpha=0.5, bins = 20)+ theme_bw()
如何将它们与刻面并排比较?
ggplot(data,aes(x= x ,group=class,fill=class)) +
geom_histogram(position="identity",
alpha=0.5,
bins = 20) +
theme_bw() +
facet_wrap(~class, scales = "free_y")
考虑以下情况,您有 800 个和 200 个观察值:
library(ggplot2)
df <- data.frame(
x = rnorm(1000, rep(c(1, 2), c(800, 200))),
class = rep(c("A", "B"), c(800, 200))
)
ggplot(df, aes(x, fill = class)) +
geom_histogram(bins = 20, position = "identity", alpha = 0.5,
# Note that y = stat(count) is the default behaviour
mapping = aes(y = stat(count)))
您可以使用 y = stat(ncount)
:
将每个组的计数缩放到最大值 1
ggplot(df, aes(x, fill = class)) +
geom_histogram(bins = 20, position = "identity", alpha = 0.5,
mapping = aes(y = stat(ncount)))
或者,您可以设置y = stat(density)
使总面积积分为1。
ggplot(df, aes(x, fill = class)) +
geom_histogram(bins = 20, position = "identity", alpha = 0.5,
mapping = aes(y = stat(density)))
请注意,在 ggplot 3.3.0 之后 stat()
可能会被 after_stat()
取代。
我正在努力解决以下问题:
我想绘制两个直方图,但由于两个 类 之一的统计数据比另一个少得多,我需要添加第二个 y-axis 以便直接比较值。
我在下面报告我目前使用的代码和结果。
提前致谢!
ggplot(data,aes(x= x ,group=class,fill=class)) + geom_histogram(position="identity",
alpha=0.5, bins = 20)+ theme_bw()
如何将它们与刻面并排比较?
ggplot(data,aes(x= x ,group=class,fill=class)) +
geom_histogram(position="identity",
alpha=0.5,
bins = 20) +
theme_bw() +
facet_wrap(~class, scales = "free_y")
考虑以下情况,您有 800 个和 200 个观察值:
library(ggplot2)
df <- data.frame(
x = rnorm(1000, rep(c(1, 2), c(800, 200))),
class = rep(c("A", "B"), c(800, 200))
)
ggplot(df, aes(x, fill = class)) +
geom_histogram(bins = 20, position = "identity", alpha = 0.5,
# Note that y = stat(count) is the default behaviour
mapping = aes(y = stat(count)))
您可以使用 y = stat(ncount)
:
ggplot(df, aes(x, fill = class)) +
geom_histogram(bins = 20, position = "identity", alpha = 0.5,
mapping = aes(y = stat(ncount)))
或者,您可以设置y = stat(density)
使总面积积分为1。
ggplot(df, aes(x, fill = class)) +
geom_histogram(bins = 20, position = "identity", alpha = 0.5,
mapping = aes(y = stat(density)))
请注意,在 ggplot 3.3.0 之后 stat()
可能会被 after_stat()
取代。