ggplot2中的瀑布图似乎无法正确显示

时间:2018-07-24 17:38:29

标签: r ggplot2

我正在尝试重新创建瀑布图,如下所示 https://vita.had.co.nz/papers/ggplot2-wires.pdf 我正在从链接中复制代码

    balance <- data.frame(event = c("Starting\nCash", "Sales", "Refunds",
                                "Payouts", "Court\nLosses", "Court\nWins", "Contracts", "End\nCash"),
                      change = c(2000, 3400, -1100, -100, -6600, 3800, 1400, -2800))

    balance$balance <- cumsum(c(0, balance$change[-nrow(balance)]))
    balance$time <- 1:nrow(balance)
balance$flow <- factor(sign(balance$change))

ggplot(balance) +
  geom_hline(yintercept = 0, colour = "white", size = 2) +
  geom_rect(aes(fill= 'red'),xmin = time - 0.45, xmax = time + 0.45, ymin = balance, ymax = balance) 
                  geom_text(aes(x = time, y = pmin(balance, balance + change) - 50, label = dollar(change)),
                                          hjust = 0.5, vjust = 1, size = 3)

  scale_x_continuous( breaks = balance$time, labels = balance$event) +
                  scale_y_continuous("Balance") +
                  scale_fill_manual(values = c("-1" = "red", "1" = "black"))

它会引发错误:Error in scale_x_continuous(breaks = balance$time, labels = balance$event) + : non-numeric argument to binary operator

每个pdf的最终输出应类似于下图

enter image description here

1 个答案:

答案 0 :(得分:1)

ggplot(balance %>% 
           mutate(flow = factor(flow, labels = c("Negative", "Positive")))) +
  geom_hline(yintercept = 0, colour = "white", size = 2) +
    geom_rect(aes(fill= flow, xmin = time - 0.45, xmax = time+0.45, ymin = change, ymax = balance), 
              color = "black") +
geom_text(aes(x = time, y = pmin(balance, balance + change) - 50, label = change),
          hjust = 0.5, vjust = 1, size = 3) +
scale_x_continuous(breaks = balance$time, labels = balance$event) +
scale_y_continuous("Balance") +
scale_fill_manual(values = c("Negative" = "red", "Positive" = "green"))

enter image description here