moodymudskipper
moodymudskipper

Reputation: 47320

How to plot empty bars for factors with no value using geom_bar?

See these 2 data.frames:

df1 <- data.frame(var=letters[1:3],val=1:3)
df2 <- df1[-1,]

Note that var is a factor in both data.frames and that level c is in df2$var

df2$var
# [1] b c
# Levels: a b c

If I use facets I get my bars filled with the expected color:

library
library(dplyr)
bind_rows(df1,df2,.id = "id") %>%
  ggplot(aes(1,val,fill=var)) +
    geom_bar(stat="identity",position="fill") +
    facet_wrap(~id)

(Sorry I can't upload charts at present time)

But if I want to do 2 separate plots, I can't keep the same color theme.

ggplot(df1,aes(1,val,fill=var)) + geom_bar(stat="identity",position="fill")
ggplot(df2,aes(1,val,fill=var)) + geom_bar(stat="identity",position="fill")

How can I fix this ?

Upvotes: 0

Views: 1125

Answers (1)

camille
camille

Reputation: 16842

Just create a manual color palette and tell your scale not to drop missing factor levels.

Also note that geom_bar(position = "identity") is the same as geom_col(); might as well go for the shorter notation.

library(ggplot2)

df1 <- data.frame(var=letters[1:3],val=1:3)
df2 <- df1[-1,]

pal <- c(a = "blue", b = "red", c = "gold")

ggplot(df1, aes(x = 1, y = val, fill = var)) +
    geom_col(position = "fill") +
    scale_fill_manual(values = pal, drop = F)

ggplot(df2, aes(x = 1, y = val, fill = var)) +
    geom_col(position = "fill") +
    scale_fill_manual(values = pal, drop = F)

Created on 2018-04-30 by the reprex package (v0.2.0).

Upvotes: 2

Related Questions