Reputation: 287
I have dataframe
DF <- data.frame(V1 = factor(c("Option 1", "Option 1", "Option 1", "Option 2", "Option 1", "Option 2", "Option 1", "Option 1", "Option 2", NA, "Option 2", "Option 1", "Option 2", "Option 1", "Option 2", "Option 1", "Option 2", "Option 1")),
Location = factor(c("California", "Georgia", "Texas", "Texas", "Georgia", "Georgia", "California", "Georgia", "Texas", "Texas", "California", "Georgia", "Mexico", "Mexico", "Mexico", "Canada", "Canada", "Canada")))
When I plot it in ggplot, it gets a little confusing as US states and two other countries are displayed side-by-side:
DF %>%
filter(!is.na(V1)) %>%
ggplot(aes(Location, ..count..)) +
geom_bar(aes(fill = V1), position = "dodge")
I can make the plot clearer by reordering the levels of the Location
variable:
DF$Location = factor(DF$Location, levels=c("Canada", "Mexico", "California", "Georgia", "Texas"))
DF %>%
filter(!is.na(V1)) %>%
ggplot(aes(Location, ..count..)) +
geom_bar(aes(fill = V1), position = "dodge")
But I'd like to label somehow that California, Georgia and Texas are US states, for example (but not necessarily) by adding "United States" underneath the names of the three states. Is there a way to do this?
Commenters below suggest this is a duplicate. I don't think so. In the cases linked to below there was already a "country"-equivalent category in the dataframe. I could of course create one, but it's time-consuming for a large dataframe. I was hoping for a way to add the "country" label just to the plot.
Upvotes: 1
Views: 1313
Reputation: 712
I would use facet_grid to separate the US states and the other locations into separate panels. Like so:
DF$isUS <- ifelse(DF$Location %in% c("California", "Georgia", "Texas"), "US States", "Rest of world")
DF %>%
filter(!is.na(V1)) %>%
ggplot(aes(Location, ..count..)) +
geom_bar(aes(fill = V1), position = "dodge") +facet_grid(~isUS, space="free", scales="free")
Upvotes: 1