Split-violin绘图报错:data需为data.frame而非字符向量求助
解决Split-Violin图绘制的"data must be a data.frame"报错
问题根源
这个报错的核心是ggplot没有接收到正确格式的数据框,大概率是你未将宽格式的输入数据转换为ggplot要求的长格式,或是在调用绘图函数时错误传入了列名字符向量而非整理后的数据框。
解决方案步骤
1. 先把数据整理为长格式
你的需求是对df从第二列开始的每一列绘图,需要先将这些列转成长格式,保留subtype和pathologic_stage作为分组变量:
library(tidyverse) # 筛选第二列及以后的列,转换为长格式 long_df <- df %>% pivot_longer(cols = 2:ncol(.), names_to = "feature", values_to = "value")
2. 确保Split-Violin的自定义Geom正确
Split-Violin不是ggplot2原生几何对象,需要先定义对应的函数(如果还没定义的话):
# 定义split-violin的geom函数 GeomSplitViolin <- ggproto("GeomSplitViolin", GeomViolin, draw_group = function(self, data, ..., draw_quantiles = NULL) { data <- transform(data, xminv = x - violinwidth * (x - xmin), xmaxv = x + violinwidth * (xmax - x)) grp <- data[1, "group"] newdata <- plyr::arrange(transform(data, x = if (grp %% 2 == 1) xminv else xmaxv), if (grp %% 2 == 1) y else -y) newdata <- rbind(newdata[1, ], newdata, newdata[nrow(newdata), ], newdata[1, ]) newdata[c(1, nrow(newdata) - 1, nrow(newdata)), "x"] <- round(newdata[1, "x"]) if (length(draw_quantiles) > 0 & !scales::zero_range(range(data$y))) { stopifnot(all(draw_quantiles >= 0), all(draw_quantiles <= 1)) quantiles <- ggplot2:::create_quantile_segment_frame(data, draw_quantiles) aesthetics <- data[rep(1, nrow(quantiles)), setdiff(names(data), c("x", "y")), drop = FALSE] aesthetics$alpha <- rep(1, nrow(quantiles)) both <- cbind(quantiles, aesthetics) quantile_grob <- GeomPath$draw_panel(both, ...) ggplot2:::ggname("geom_split_violin", grid::grobTree(GeomPolygon$draw_panel(newdata, ...), quantile_grob)) } else { ggplot2:::ggname("geom_split_violin", GeomPolygon$draw_panel(newdata, ...)) } }) geom_split_violin <- function(mapping = NULL, data = NULL, stat = "ydensity", position = "identity", ..., draw_quantiles = NULL, trim = TRUE, scale = "area", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE) { layer(data = data, mapping = mapping, stat = stat, geom = GeomSplitViolin, position = position, show.legend = show.legend, inherit.aes = inherit.aes, params = list(trim = trim, scale = scale, draw_quantiles = draw_quantiles, na.rm = na.rm, ...)) }
3. 绘制Split-Violin图
用整理好的长数据框绘图,按subtype设置x轴,pathologic_stage作为填充分组:
ggplot(long_df, aes(x = subtype, y = value, fill = pathologic_stage)) + geom_split_violin(trim = FALSE) + facet_wrap(~feature) + # 每个特征单独生成子图,匹配示例图效果 labs(x = "Subtype", y = "Value", fill = "Pathologic Stage") + theme_bw()
关键注意点
- 不要直接把列名(字符向量)传给ggplot的
data参数,必须传入整理后的长格式数据框 facet_wrap(~feature)会自动为第二列的每个特征生成独立子图,和你期望的示例图结构一致
内容的提问来源于stack exchange,提问作者melolilili
相关产品推荐
相关产品推荐

