我用facet_grid
做了一系列直方图,我希望网格中的每个直方图都有相同数量的类,例如下面的例子中,例如6节课。下面这个例子中的问题是binwidth = diff(range(x$data))/6)
根据a,b和c的整体范围定义类,即为所有三个方面定义一个binwidth。
如何为构面a,b和c单独定义binwidth?
require("ggplot2")
a <- c(1.21,1.57,1.21,0.29,0.36,0.29,0.93,0.26,0.28,0.48,
0.12,0.38,0.83,0.82,0.41,0.69,0.25,0.98,0.52,0.11)
b <- c(0.42,0.65,0.17,0.38,0.44,0.01,0.01,0.03,0.15,0.01)
c <- c(1.09,3.55,1.07,4.55,0.55,0.11,0.72,0.66,1.22,3.04,
2.01,0.64,0.47,1.33,3.44)
x <- data.frame(data = c(a,b,c), variable = c(rep("a",20),rep("b",10),rep("c",15)),area="random")
qplot(data, data = x, geom = "histogram", binwidth = diff(range(x$data))/6) +
facet_grid(area~variable, scales = "free")
答案 0 :(得分:3)
这不是最佳,但您可以在不同的层中进行直方图:
ggplot(x, aes(x=data)) +
geom_histogram(data=subset(x, variable=="a"), binwidth=.1) +
geom_histogram(data=subset(x, variable=="b"), binwidth=.2) +
geom_histogram(data=subset(x, variable=="c"), binwidth=.5) +
facet_grid(area~variable, scales="free")
答案 1 :(得分:1)
一种方法是以您希望的方式预先汇总您的数据,然后创建绘图。
在您的情况下,您需要使用函数cut()
对变量进行分箱。包dplyr
对此很方便,因为它允许您为每组数据指定mutate函数:
library(dplyr)
zz <- x %>%
group_by(variable) %>%
mutate(
bins = cut(data, breaks=6)
)
qplot(bins, data = zz, geom = "histogram", fill=I("blue")) +
facet_grid(area~variable, scales = "free") +
theme(axis.text.x = element_text(angle=90))