Plotting proportional frequencies with ggplot2 but leaving out some categories of data

Viewed 22

I am trying to create a ggplot with proportional frequencies. Here is a reproducible plot:

aa <- rep(c("Sta 1", "Sta 2", "Sta 3", "Sta 4"), each = 4)
bb <- rep(c("none", "minimal", "moderate", "major"), 4)                  
cc <- sample(1:40, 16, replace=F)

df <- data.frame(aa,bb,cc)


library(ggplot2)

cols <- c("none" = "light green", "minimal" = "dark green", "moderate" = "light blue", "major" = "dark blue")

plot <- ggplot(df, aes(fill=bb, y = cc, x = aa))
plot + geom_bar(position = "fill", stat = "identity") + scale_colour_manual(values = cols, aesthetics = c("colour", "fill")) 

I was asked to leave out the categories "none" and "minimal", but still include the overall proportion. I have a workaround to set the category colors as transparent with NAs:

cols <- c("none" = NA, "minimal" = NA, "moderate" = "light blue", "major" = "dark blue")

I am not so experienced with this, but am wondering if there is a more elegant solution for leaving out chunks of data?

1 Answers

Try this:

library(ggplot2)

cols <- c("none" = "light green", "minimal" = "dark green", "moderate" = "light blue", "major" = "dark blue")

plot <- ggplot(df, aes(fill=bb, y = cc, x = aa))
plot + geom_bar(position = "fill", stat = "identity") +
  scale_colour_manual(values = cols, aesthetics = c("colour", "fill"),
                      breaks=c('moderate','major'))

Output:

enter image description here

One option can be:

#Code 2
plot <- ggplot(subset(df,!bb %in% c("none","minimal")), aes(fill=bb, y = cc, x = aa))
plot + geom_bar(position = "fill", stat = "identity") + scale_colour_manual(values = cols, aesthetics = c("colour", "fill")) 

Output:

enter image description here

Or this option:

#Code 3
plot <- ggplot(df, aes(fill=bb, y = cc, x = aa))
plot + geom_bar(position = "fill", stat = "identity") +
  scale_colour_manual(values = cols, aesthetics = c("colour", "fill"),
                      breaks=c('moderate','major'),
                      limits=c('moderate','major')) 

Output:

enter image description here

Related