有没有支持facet_wrap/grid的R语言瀑布图绘制包?
支持分面的瀑布图解决方案
方案1:使用tidywaterfall包(基于ggplot2,原生支持分面)
tidywaterfall是基于ggplot2开发的瀑布图工具,完全兼容ggplot2的分面函数facet_wrap()/facet_grid(),可以直接通过分面参数实现多组瀑布图展示。
示例代码:
# 安装并加载包 install.packages("tidywaterfall") library(tidywaterfall) library(ggplot2) # 构造带分组的示例数据 set.seed(123) df <- data.frame( group = rep(c("A", "B"), each = 5), category = rep(paste0("Item", 1:5), 2), value = c(30, -10, 15, -5, 20, 25, -8, 12, -3, 18) ) # 绘制带分面的瀑布图 tidywaterfall(df, x = category, value = value, fill = category) + facet_wrap(~group) + theme_minimal()
方案2:用ggplot2手动构建瀑布图并实现分面
如果不想引入新包,可以直接用ggplot2手动计算瀑布图的位置参数,再结合分面功能实现需求:
示例代码:
library(ggplot2) library(dplyr) # 构造带分组的示例数据 set.seed(123) df <- data.frame( group = rep(c("A", "B"), each = 5), category = rep(paste0("Item", 1:5), 2), value = c(30, -10, 15, -5, 20, 25, -8, 12, -3, 18) ) # 计算瀑布图所需的累积值、起始/结束位置 df <- df %>% group_by(group) %>% mutate( cumulative = cumsum(value), start = lag(cumulative, default = 0), end = cumulative ) %>% ungroup() # 绘制分面瀑布图 ggplot(df, aes(x = category)) + geom_rect(aes( xmin = as.integer(factor(category)) - 0.4, xmax = as.integer(factor(category)) + 0.4, ymin = pmin(start, end), ymax = pmax(start, end), fill = ifelse(value >= 0, "positive", "negative") )) + geom_text(aes(y = end, label = value), vjust = ifelse(df$value >= 0, -0.5, 1.5)) + facet_wrap(~group) + theme_minimal() + labs(x = "Category", y = "Value")
内容的提问来源于stack exchange,提问作者anderwyang
相关产品推荐
相关产品推荐

