r-使用空数据框架绘制瀑布图的错误



我的工作条件下有瀑布图。但是,当数据框为空时,它会返回错误。当没有针对指定条件的数据时,数据框可以为空。

以下是我用来绘制瀑布图表的代码。我想打印"指定的报告没有数据"

而不是错误。
#dataset <- data.frame(TotalHeadcount = c(-417, -12, 276, -276, 787, 14), Category =  LETTERS[1:6])
dataset <- data.frame(TotalHeadcount = NA, Category =  NA)[numeric(0), ]
dataset
dataset$SortedCategory <- factor(dataset$`Category`, levels = dataset$`Category`)
dataset$id <- seq_along(dataset$TotalHeadcount)
dataset$type <- ifelse(dataset$TotalHeadcount > 0, "in",   "out")
dataset[dataset$SortedCategory %in% c("A", "F"), "type"] <- "net"
dataset$type <- factor(dataset$type, levels = c("out", "in", "net"))
dataset$end <- cumsum(dataset$`TotalHeadcount`)
dataset$end <- c(head(dataset$end, -1), 0)
dataset$start <- c(0, head(dataset$end, -1))
dataset$value <-dataset$`TotalHeadcount`
library(ggplot2)
strwr <- function(str) gsub(" ", "n", str)
ggplot(dataset, aes(fill = type))+ geom_rect(aes(x = SortedCategory,  xmin = id - 0.45, xmax = id + 0.45, ymin = end,   ymax = start))+ scale_x_discrete("", breaks = levels(dataset$SortedCategory), labels = strwr(levels(dataset$SortedCategory)))+ theme_bw()+ theme(panel.border = element_blank(), panel.grid.major = element_blank(), axis.line = element_line(colour = "gray"))+guides(fill=FALSE)

在这里,我已经评论了正常工作的实际数据帧数据。而是我添加了一个空的数据框,此代码给出了错误。

任何帮助将不胜感激。

问候,Akash

您要在哪里显示错误消息?这有效吗?

if(nrow(dataset) == 0) {
  print("The specified report does not have data")
} else {
  ggplot(dataset, ...
}

最新更新