`levels

The answers here are good, but they are missing an important point. Let me try and describe it. R is a functional language and does not like to mutate its objects. But it does allow assignment statements, using replacement functions: levels(x) <- y is equivalent to x <- `levels<-`(x, y) The trick is, this rewriting … Read more

ggplot2 keep unused levels barplot

You need to set drop=FALSE on both scales (fill and x) like this: library(ggplot2) df <- data.frame(type=c(“A”, “A”, “A”, “B”, “B”), group=rep(“group1”, 5)) df1 <- data.frame(type=c(“A”, “A”, “A”, “B”, “B”, “A”, “A”, “C”, “B”, “B”), group=c(rep(“group1”, 5),rep(“group2”, 5))) df$type <- factor(df$type, levels=c(“A”,”B”, “C”)) df1$type <- factor(df1$type, levels=c(“A”,”B”, “C”)) plt <- ggplot(df, aes(x=type, fill=type)) + geom_bar(position=’dodge’) … Read more

tech