使用waterfalls包绘制瀑布图:长X轴标签换行后排序错乱求助
问题解决:waterfalls包瀑布图X轴标签换行后保留原始顺序
问题原因
使用scale_x_discrete添加换行标签时,会覆盖waterfall函数自动生成的X轴刻度顺序,默认按字母排序,同时触发"重复X轴刻度"的警告。
解决方案一:指定X轴刻度的原始顺序
在scale_x_discrete中通过limits参数明确指定刻度顺序(包含原数据的Factors和计算出的Total),同时设置换行标签:
library(waterfalls) library(stringr) # 加载数据 wf <- structure(list(Factors = c("Start", "Differential A", "Move", "EQ", "Differential (Premium)", "Transportation"), Cost = c(119.19, -25.4, -0.832, -5.7, 4.93, -7.37)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -6L)) # 定义X轴刻度的原始顺序(加上自动生成的Total) x_axis_order <- c(wf$Factors, "Total") # 绘图并设置换行标签 waterfall(wf, calc_total=TRUE, rect_width=.4, fill_by_sign=TRUE, total_rect_color="grey", rect_border=NA) + labs(y="Cost", title ="Waterfall", x=NULL) + scale_x_discrete( limits = x_axis_order, labels = function(x) str_wrap(x, width = 10) )
解决方案二:提前处理标签再绘图
直接在数据阶段将Factors转换为换行后的字符串,绘图时无需额外修改刻度,自然保留原始顺序:
library(waterfalls) library(stringr) # 加载数据 wf <- structure(list(Factors = c("Start", "Differential A", "Move", "EQ", "Differential (Premium)", "Transportation"), Cost = c(119.19, -25.4, -0.832, -5.7, 4.93, -7.37)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -6L)) # 提前对标签进行换行处理 wf$Factors <- str_wrap(wf$Factors, width = 10) # 直接绘图 waterfall(wf, calc_total=TRUE, rect_width=.4, fill_by_sign=TRUE, total_rect_color="grey", rect_border=NA) + labs(y="Cost", title ="Waterfall", x=NULL)
内容的提问来源于stack exchange,提问作者zxcvfi
相关产品推荐
相关产品推荐

