简体   繁体   中英

Overlapping bar plot in ggplot2

I'm trying to hide a variable in a stacked bar chart in a dataset.
Below is the dataset:

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM