1

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.

KaC
  • 287
  • 1
  • 5
  • 19
  • 1
    You may check [here](https://stackoverflow.com/questions/20571306/multi-row-x-axis-labels-in-ggplot-line-chart) – akrun Jun 06 '18 at 20:21
  • 1
    Possible duplicate of [Multi-row x-axis labels in ggplot line chart](https://stackoverflow.com/questions/20571306/multi-row-x-axis-labels-in-ggplot-line-chart) – Bjoern Rennhak Jun 06 '18 at 20:27
  • My problem is a little different than the one you linked to (or the one here: https://stackoverflow.com/questions/18165863/multirow-axis-labels-with-nested-grouping-variables). In those cases 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. – KaC Jun 06 '18 at 20:27

1 Answers1

1

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

enter image description here

Luke Hayden
  • 692
  • 4
  • 8