bar plot with named groups on x-axis in ggplot2?

Viewed 731

it want to make a plot of this type in ggplot, but cant get it to work (made in excel):

enter image description here

So that there are cities on the x-axis, but they are arranged according to which state they are in. The color of each bar is based on some third property, for example size of city (large, small or medium), and the y-axis is a measurement of whatever! A legend of (large, small, medium) should be included, just isn't in the figure I pasted here.

Example data:

state <- c(rep("Texas",3),rep("Colorado",3),rep("Nevada",3))
city <- c("Houston","Austin","Dallas","Denver","Boulder","Aspen","Reno","Sparks","Henderson")
size <- c(rep(c("large","medium","small"),3))
value <- runif(9, 10,50)
df <- data.frame(state,city,size, value)

So far, I have done this:

plot <- ggplot(df, aes(x=State, y=value)) + 
  geom_bar(aes(fill=size),position = "dodge", stat = "identity", color="black")
plot

But then each bar is not labeled with the city name. Any ideas?

1 Answers

Answer

(Credit to https://dmitrijskass.netlify.app/2019/06/30/multi-level-labels-with-ggplot2/ )

Use facet_grid:

ggplot(df, aes(x=city, y = value)) + 
  geom_col() +
  facet_grid(~ state, 
             scales = "free_x",
             space = "free_x",
             switch = "x")

enter image description here

More complete version

ggplot(df, aes(x=city, y = value)) + 
  geom_col() +
  facet_grid(~ state, 
             scales = "free_x",
             space = "free_x",
             switch = "x") +
  theme(panel.spacing = unit(0, units = "cm"), # removes space between panels
        strip.placement = "outside", # moves the states down
        strip.background = element_rect(fill = "white") # removes the background from the state names

enter image description here

Related