在 facet_wrap ggplot 中突出显示没有数据的位置
Highlight positions without data in facet_wrap ggplot
在 ggplot 中分面条形图时,x 轴包括所有因子水平。但是,并非所有级别都可能出现在每个组中。此外,可能存在零值,因此仅从条形图无法区分没有数据的 x 轴值和具有零 y 值的 x 轴值。考虑以下示例:
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年没钓到,reader就分不出来了。我想在 2011 年的情节中添加类似 "no data" 的内容。也许可以填充缺少数据的行,生成另一列包含要添加的所需文本,然后通过 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)
或者,您也可以让构面省略未使用的 x-axis 值:
ggplot(df, aes(x=year, y=value)) +
geom_bar(stat="identity") +
facet_wrap(~site, scales = "free_x")
在 ggplot 中分面条形图时,x 轴包括所有因子水平。但是,并非所有级别都可能出现在每个组中。此外,可能存在零值,因此仅从条形图无法区分没有数据的 x 轴值和具有零 y 值的 x 轴值。考虑以下示例:
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年没钓到,reader就分不出来了。我想在 2011 年的情节中添加类似 "no data" 的内容。也许可以填充缺少数据的行,生成另一列包含要添加的所需文本,然后通过 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)
或者,您也可以让构面省略未使用的 x-axis 值:
ggplot(df, aes(x=year, y=value)) +
geom_bar(stat="identity") +
facet_wrap(~site, scales = "free_x")