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

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

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

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With