R语言 如何使用填充组绘制带有百分比的分面直方图?

hgc7kmma  于 2023-07-31  发布在  其他
关注(0)|答案(1)|浏览(109)

我想绘制一个百分比直方图方面和一个组填充变量。这里讨论了类似的事情,但没有fill变量。Percentage histogram with facet_wrap
不幸的是,原始的密度解产生了奇怪的结果。在下面的代码中:第一个geom_hist行生成不正确的组R行。第二个geom_hist生成正常计数。如何打印正确的分面百分比?

values <- sample(c(4,8,16,32,64,128,256,512),1000,replace=TRUE)
groups <- sample(c("A","B","C","D"),1000,replace=TRUE)
daf <- data.frame(group=groups,value=values)
daf$state <- "S"
daf$state[daf$group == "A" & daf$value > 16] <- "R"
daf$state[daf$group == "B" & daf$value > 64] <- "R"
daf$state[daf$group == "C" & daf$value > 32] <- "R"
daf$state[daf$group == "D" & daf$value > 256] <- "R"

p <- ggplot(daf, aes(x=value,fill=state)) +
 geom_histogram(aes(y = stat(density)*0.5),binwidth=0.5) +
  # geom_histogram(aes(y = stat(count)),binwidth=0.5) +
  scale_x_continuous(name = "log2-trans",trans="log2",labels = scales::math_format(2^.x, format = log2),breaks = c(0.015625,0.03125,0.0625,0.125,0.25,0.5,0,1,2,4,8,16,32,64,128,256,512)) +
  scale_y_continuous(name = "Count")+
  facet_wrap(~ group,nrow=5,ncol=3,scales = "free")+
  theme_minimal()+
  theme(legend.position = "bottom")
p

字符串

kq0g1dla

kq0g1dla1#

通过将stateMap到fill上,可以根据state的面 * 和 * 类别计算密度。相反,如果您希望在两个状态的所有bin上计算密度,则可以使用geom_histogram中的after_stat设置fill颜色,或者作为第二个选项,根据计数手动计算“密度”或百分比:

library(ggplot2)

set.seed(123)

ggplot(daf, aes(x = value, fill = state)) +
  geom_histogram(
    aes(y = after_stat(
      ave(count, PANEL, FUN = \(x) x / sum(x))
    )),
    binwidth = 0.5
  ) +
  scale_x_continuous(
    name = "log2-trans", trans = "log2",
    labels = scales::math_format(2^.x, format = log2),
    breaks = c(
      0.015625, 0.03125, 0.0625, 0.125, 0.25,
      0.5, 0, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512
    )
  ) +
  scale_y_continuous(name = "Count") +
  facet_wrap(~group, nrow = 5, ncol = 3, scales = "free") +
  theme_minimal() +
  theme(legend.position = "bottom")

字符串


的数据

相关问题