Reputation: 11
I'm trying to hide a variable in a stacked bar chart in a dataset.
Below is the dataset:
Upvotes: 1
Views: 387
Reputation: 173793
First convert Ethnic.group
to a factor, then filter the data frame to only contain the entries where Ethnic.group != "Asian"
. This will mean that Ethnic.group
"remembers" that there is a category called "Asian", even though it contains no actual "Asian" values.
To use this "memory" in your plot, add + scale_fill_discrete(drop = FALSE)
to include all factor levels even when some of the levels are not represented in the data.
These two steps will keep "Asian" in the legend as a possible value, but without any actual entries on the plot, and maintain the colours that were present in your original plot.
popByAgeEthnicity %>%
mutate(Ethnic.group = factor(Ethnic.group)) %>%
filter(Ethnic.group != "Asian") %>%
ggplot(aes(Age.group, Pop, fill = Ethnic.group)) +
geom_col() +
scale_fill_discrete(drop = FALSE)
As a side note, writing geom_bar(stat = "identity")
is just a long way of writing geom_col()
Upvotes: 3