我正在创建瀑布图。我想在条上方显示数据标签。我当前的代码正在基于变量“值”的位置显示数据标签。标签的位置应基于“ end”列。标签的值应基于变量“值”。
require(tidyverse)
df <- tibble(
label = c("Forecast YTD", "Gross Accelerated Cashflows", "Gross Delayed Cashflows",
"Gross Asset Outperformance", "Gross Asset Underperformance"),
value = c(0.664, 0.554, -0.515, 0.332, -0.034))
df <- df %>%
mutate(
end = cumsum(value),
start = dplyr::lag(end, default = 0),
col = c("neg", "pos", "total")[c(3, (value[-1]>0)+1)],
id = seq(1, n())
) %>%
bind_rows(summarise(., label = "Total Actual Collections", start = 0,
end = last(end), id = n()+1L, col = "total"))
df %>% ggplot(aes(x=label, y=value, fill = col)) +
geom_rect(aes(x = label, xmin = id -0.45, xmax = id + 0.45, ymin = end, ymax = start)) +
ylab("% Gross Cash Forecasted YTD") + xlab("") +
geom_text(aes(label = scales::percent(value, accuracy = 1)), vjust = -0.5) +
scale_y_continuous(labels = scales::percent) +
theme(legend.position = "none") +
scale_fill_manual(values = c("#bfbfbf", "#90a9e3", "#002060"))
您非常亲密!一个问题是您要根据“标签”设置百分比标签的x位置(geom_text
从主调用继承到ggplot
),而条形图的x位置是根据“ id”计算的”列。由于ggplot
根据标签按字母顺序排列x轴值,因此这会使您的轴与“ id”中的值不同步。解决此问题的一种方法是将“标签”转换为有序因子。然后,ggplot
将获取订单数据,并且您的条和标签都将同步。
另一个问题是,标签的y值应设置为每一列的“开始”或“结束”最大值,以较大者为准。以下代码解决了两个问题(注释行):
df <- tibble(
label = c("Forecast YTD", "Gross Accelerated Cashflows", "Gross Delayed Cashflows",
"Gross Asset Outperformance", "Gross Asset Underperformance"),
value = c(0.664, 0.554, -0.515, 0.332, -0.034))
df <- df %>%
mutate(
end = cumsum(value),
start = dplyr::lag(end, default = 0),
col = c("neg", "pos", "total")[c(3, (value[-1]>0)+1)],
id = seq(1, n()),
max = pmax(start, end, na.rm = T) # the greater of "start" or "end" for each row
) %>%
bind_rows(summarise(., label = "Total Actual Collections", start = 0,
end = last(end), id = n()+1L, col = "total")) %>%
mutate(label = factor(label, label, ordered = T)) # convert labels to ordered factor
对您的绘图代码进行一些细微更改:
df %>% ggplot(aes(x=label, y=value, fill = col)) +
geom_rect(aes(x = label, xmin = id -0.45, xmax = id + 0.45, ymin = end, ymax = start)) +
ylab("% Gross Cash Forecasted YTD") + xlab("") +
geom_text(aes(label = scales::percent(value, accuracy = 1), y = max), vjust = -0.5) +
scale_y_continuous(labels = scales::percent) +
theme(legend.position = "none") +
scale_fill_manual(values = c("#bfbfbf", "#90a9e3", "#002060"))