我正在使用ggplot2创建多个图表,并使用facet_grid()按年分类。我想在每个特定年份添加文本,总值低于0.但是,如果没有数据,我不希望出现一年(参见下面的示例)。图表b应该只显示2015年,因为它没有2016年的数据。我也有重复文本的问题(即使我已经指定了一个特定的标签)。
year <- c(2015,2015,2015,2016,2016,2016,2015,2015,2015)
group <- c("a","a","a","a","a","a","b","b","b")
value <- c(-10,20,0,10,20,0,-10,5,15)
df <- as.data.frame(cbind(year,group,value))
df$value <- as.numeric(as.character(df$value))
y <- split(df, df$group)
i=1
for (i in 1:length(y)) {
y[[i]] <- y[[i]][order(y[[i]]$year,y[[i]]$value),]
p <- ggplot(y[[i]], aes(seq(1,nrow(y[[i]]),by=1),value))+
geom_area(position="identity", alpha=0.5)+
ggtitle(paste0(names(y[i])))+
ylab("value")+
facet_grid(year~.)+
xlab("")
#get subsets for adding totals by year
all_15 <- subset(y[[i]],y[[i]]$year == 2015)
all_15$value <- as.numeric(as.character(all_15$value))
all_16 <- subset(y[[i]],y[[i]]$year == 2016)
all_16$value <- as.numeric(as.character(all_16$value))
#total below by year
below15 <- paste0("Total Cost Below - ", round(abs(sum(all_15$value[all_15$value<0])),2))
below16 <- paste0("Total Cost Below - ", round(abs(sum(all_16$value[all_16$value<0])),2))
#add text to show total below for each year
ann_text <- data.frame(-Inf, value=-Inf,lab = below15,
year = factor(2015,levels = c(2015,2016)))
ann_text2 <- data.frame(-Inf, value=-Inf,lab = below16,
year = factor(2016,levels = c(2015,2016)))
q <- p + geom_text(data = ann_text,label = ifelse(nrow(y[[i]][y[[i]]$year == 2015,])>1,levels(ann_text$lab), ""), hjust = 0, vjust = -1)
q2 <- q + geom_text(data = ann_text2,label = ifelse(nrow(y[[i]][y[[i]]$year == 2016,])>1,levels(ann_text2$lab), ""), hjust = 0, vjust = -1)
print(q2)
}
第一张图 第二张图