r - 突出显示facet_wrap ggplot中没有数据的位置

标签 r ggplot2 bar-chart facet geom-text

当在 ggplot 中分面条形图时,x 轴包括所有因子水平。然而,并非所有级别都可能出现在每个组中。此外,可能存在零值,因此仅从条形图中无法区分没有数据的 x 轴值和 y 值为零的值。考虑以下示例:

 library(tidyverse)
 set.seed(43)
 site <- c("A","B","C","D","E") %>% sample(20, replace=T) %>% sort()
 year <- c("2010","2011","2012","2013","2014","2010","2011","2012","2013","2014","2010","2012","2013","2014","2010","2011","2012","2014","2012","2014")
 isZero = rbinom(n = 20, size = 1, prob = 0.40)
 value <- ifelse(isZero==1, 0, rnorm(20,10,3)) %>% round(0)
 df <- data.frame(site,year,value)

ggplot(df, aes(x=year, y=value)) +
  geom_bar(stat="identity") +
  facet_wrap(~site)

这是鱼类普查数据,并非所有年份的所有地点都进行了捕鱼,但有时没有捕获到鱼。因此需要区分这两种情况。例如,2010 年 C 点没有捕捞,2011 年也没有捕捞,读者无法区分。我想在 2011 年的图中添加“无数据”之类的内容。也许可以填充缺少数据的行,生成另一列并添加所需的文本,然后通过 geom_text< 包含此内容

最佳答案

这是您建议的方法的示例:

# Tabulate sites vs year, take zero entries
tab <- table(df$site, df$year)
idx <- which(tab == 0, arr.ind = T)

# Build new data.frame
missing <- data.frame(site = rownames(tab)[idx[, "row"]],
                      year = colnames(tab)[idx[, "col"]],
                      value = 1,
                      label = "N.D.") # For 'no data'

ggplot(df, aes(year, value)) +
  geom_col() +
  geom_text(data = missing, aes(label = label)) +
  facet_wrap(~site)

enter image description here

或者,您也可以让面忽略未使用的 x 轴值:

ggplot(df, aes(x=year, y=value)) +
  geom_bar(stat="identity") +
  facet_wrap(~site, scales = "free_x")

enter image description here

关于r - 突出显示facet_wrap ggplot中没有数据的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58274821/

相关文章:

r - 矩阵中的 for 循环 - 相对频率

r - 更改 ggplot 中的千位分隔符

r - 标准化 ggplot 中覆盖密度图的 x 尺度

python - 如何创建一个可以从中创建条形图的系列

r - split apply combine w/function 或 purrr package pmap?

RStudio:构建和重新加载向描述文件中的 'suggests' 字段添加空行

python - 如何从数据框制作 3D 条形图

python - 如何旋转 matplotlib 条形图?

r - 使用 RecordLinkage 在连续存储的数据上删除唯一对

r - ggplot 中的分组条形图