user8491385
user8491385

Reputation: 443

Order of X-axis Labels GGPLOT

I have the following input data.

sample_data <- data.frame(city = c("a", "b", "c","d", "a", "b", "c", "d"), value = c(10, 11, 17, 12, 13, 14, 11, 8), type = c(1,1,1,1,2,2,2,2), country = c("c1", "c2", "c1", "c1", "c2", "c2", "c1", "c1"))

And want to create plots within ggplot that splits the data by type (so two sets of bar charts). I want the order of the bar charts to be grouped by the colours together. So below the right hand chart would group the blue and red bars to be next to each other. I have a large number of variables so manually moving them around would not be an option. The code I used for the charts was:

sample_data <- sample_data %>% 
     mutate(city2 = factor(city, levels=city[order(country)]))
ggplot(sample_data) + 
    geom_col(aes(x=city2, y=value, colour=country, fill=country)) + facet_wrap(~type)

enter image description here

Upvotes: 0

Views: 754

Answers (1)

Z.Lin
Z.Lin

Reputation: 29095

I note that in different facets, the same city (x-axis variable) may be associated with different fill colours, which suggests that the order of variables could be different in each facet, in which case specifying its factor order won't work.

Here's a workaround that specifies the x-axis order based on the fill variable, & adds a fake x-axis to the plot:

library(dplyr)

sample_data <- sample_data %>%
  group_by(type) %>%
  arrange(country) %>%
  mutate(x = row_number()) %>%
  ungroup()

ggplot(sample_data,
       aes(x = x, y = value, fill = country, label = city)) +
  geom_col() +
  geom_text(aes(y = 0), nudge_y = -1) +      # fake x-axis
  facet_wrap(~type) +
  theme(axis.text.x = element_blank(),       # hide x-axis labels
        axis.ticks.x = element_blank(),      # hide x-axis tick marks
        panel.background = element_blank())  # white background for easier reading

enter image description here

Upvotes: 1

Related Questions