junjunlab / scRNAtoolVis

Useful functions to make your scRNA-seq plot more cool!
Other
258 stars 27 forks source link

画细胞比例图,如何指定分组顺序? #48

Open terry676L opened 1 month ago

terry676L commented 1 month ago

scRNAtoolVis这个包画比例图,如何指定分组顺序吗?factor指定好像没起作用

terry676L commented 1 month ago

cellRatioPlot(object = scobj, sample.name = "group", celltype.name = "celltype", fill.col = use_colors, flow.curve = 0.5, levels = c())

cellRatioPlot <- function( object = NULL, sample.name = NULL, celltype.name = NULL, col.width = 0.7, flow.alpha = 0.25, flow.curve = 0, fill.col = NULL, levels = NULL) {

获取元数据

meta <- object@meta.data

如果指定了levels,则设置因子水平

if (!is.null(levels)) { meta[[sample.name]] <- factor(meta[[sample.name]], levels = levels) }

计算百分比比率

ratio.info <- meta %>% dplyr::group_by(.data[[sample.name]], .data[[celltype.name]]) %>% dplyr::summarise(num = n()) %>% dplyr::mutate(rel_num = num / sum(num))

设置颜色

if (is.null(fill.col)) { fill.col <- jjAnno::useMyCol("paired", n = length(unique(meta[, celltype.name]))) }

绘图

p <- ggplot2::ggplot( ratio.info, ggplot2::aes_string(x = sample.name, y = "rel_num") ) + ggplot2::geom_col( ggplot2::aes_string(fill = celltype.name), width = col.width ) + ggalluvial::geom_flow( ggplot2::aes_string( stratum = celltype.name, alluvium = celltype.name, fill = celltype.name ), width = 0.5, alpha = flow.alpha, knot.pos = flow.curve ) + ggplot2::theme_bw() + ggplot2::coord_cartesian(expand = 0) + ggplot2::scale_y_continuous(labels = scales::label_percent()) + ggplot2::scale_fill_manual( values = fill.col, name = "Cell Type" ) + ggplot2::theme( panel.grid = ggplot2::element_blank(), axis.text = ggplot2::element_text(size = ggplot2::rel(1.2), color = "black"), axis.title = ggplot2::element_text(size = ggplot2::rel(1.5), color = "black"), legend.text = ggplot2::element_text(size = ggplot2::rel(1.2), color = "black"), legend.title = ggplot2::element_text(size = ggplot2::rel(1.5), color = "black") ) + ggplot2::xlab("") + ggplot2::ylab("Cell percent ratio")

return(p) }

terry676L commented 1 month ago

修改函数,增加levels,已解决!

junjunlab commented 1 month ago

你可以重新安装一下,使用 sample.order 指定样本顺序。