dittoSeq icon indicating copy to clipboard operation
dittoSeq copied to clipboard

drop unused levels in barplot

Open cstrlln opened this issue 9 months ago • 1 comments

wanted to know what would be the simplest way of dropping unused levels in barplots, specially when splitting by different variables this gets tricky. Thank you!

cstrlln avatar Mar 16 '25 00:03 cstrlln

Hmmmm that's a great question. I'm not sure if there is a good way... I think you've just highlighted a hole in the function's functionality that I'd wanna fix.

Perhaps I'd be able to transfer over the groupings.drop.unused functionality that I specifically added to dittoDotPlot() and dittoPlotVarsAcrossGroups() easily... I'll look into it and follow up here.

In the meantime, either 1) getting rid of retain.factor.levels but that punts your ordering =/, OR 2) making a copy of your metadata data.frame and subsetting externally to where you can manually adjust the factor levels while keeping retain.factor.levels = TRUE. Not great either way. For "2)" though, I'd recommend dittoViz's barPlot function cuz then you don't need to copy and subset the whole single-cell object in achieving this purpose, just the metadata. And then maybe something like this for trimming the levels before plotting:

trim_levels <- function(factor_data) {
    levs_all <- levels(factor_data)
    levs_used <- unique(as.character(factor_data))
    factor(
        factor_data,
        levels = levs_all[levs_all %in% levs_used]
    )
}

df_subset$<column> <- trim_levels(df_subset$<column>)

dtm2451 avatar Mar 17 '25 21:03 dtm2451