【发布时间】:2014-01-16 17:35:08
【问题描述】:
我正在尝试使用我在互联网上找到并改编的以下代码来绘制一些瀑布图:
waterfall <- function(balance){
balance$desc <- factor(balance$desc, levels = balance$desc)
balance$id <- seq_along(balance$amount)
balance$type <- ifelse(balance$amount > 0, "increase","decrease")
balance[balance$id %in% c(1,dim(balance)[1]),"type"] <- "net"
balance$end <- cumsum(balance$amount)
balance$end <- c(head(balance$end, -1), 0)
balance$start <- c(0, head(balance$end, -1))
balance <- balance[, c(3, 1, 4, 6, 5, 2)]
balance
balance$type <- factor(balance$type, levels = c("decrease","increase", "net"))
p1 <- ggplot(balance, aes(desc, fill = type)) +
geom_rect(aes(x = desc,xmin = id - 0.45, xmax = id + 0.45, ymin = end,ymax = start))+
xlab("") +
ylab("") +
geom_text(subset = .(type == "increase"), aes(id,end, label = comma(amount)), vjust = 1, size = 4,fontface="bold") +
geom_text(subset = .(type == "decrease"), aes(id,end, label = comma(amount)), vjust = -0.3,size = 4,fontface="bold")+
geom_text(data = subset(balance,type == "net" & id == min(id)), aes(id, end, label = comma(end), vjust = ifelse(end <start, 1, -0.3)), size = 4,fontface="bold") +
geom_text(data = subset(balance,type == "net" & id == max(id)), aes(id, start, label = comma(start), vjust = ifelse(end < start, -0.3, 1)), size = 4,fontface="bold")+
theme_bw()+
theme(legend.position = "none")
return(p1)
}
如果我在以下示例中使用它,我对结果非常满意
balance <- data.frame(desc = c("Starting Cash","Sales", "Refunds", "Payouts", "Court Losses","Court Wins", "Contracts", "End Cash"),
amount = c(2000, 3400, -1100, -100, -6600, 3800, 1400, 2800))
但如果我想绘制一个仅增加(分别减少)的瀑布,例如在以下示例中
balance <- data.frame(desc = c("Starting Cash", "Court Losses","Court Wins", "Contracts", "End Cash"),
amount = c(2000, -1100, -100, -6600, 2800))
然后我有一个错误
Error in if (nrow(layer_data) == 0) return() : argument is of length zero
我猜它与geom_text中的子集参数有关,但我不知道如何处理子集为空的情况。
我还有第二个问题。我对第一种情况下的三种颜色感到满意。但是,如果我在第二个示例中运行代码,通过删除代码的错误部分,我会得到一个图表,其中只有两种颜色与前一种情况不同。是否可以像第一个示例一样将颜色固定为蓝色/红色/绿色?
谢谢。
【问题讨论】:
-
能否提供逗号函数或包,使其成为可独立复制的代码块?
-
很抱歉。逗号函数来自“scales”包。谢谢。
-
你确定吗?我在“秤”中找不到该功能