ggplot2 中 x 轴上带有命名组的条形图?

Yun*_*Gud 3 r bar-chart ggplot2

它想在 ggplot 中绘制这种类型的图,但无法让它工作(在 excel 中制作):

在此输入图像描述

因此,x 轴上有城市,但它们是根据它们所处的状态排列的。每个条形的颜色基于某些第三个属性,例如城市的大小(大、小或中),以及y 轴是任何东西的测量!应包含(大、小、中)的图例,只是不在我粘贴到此处的图中。

示例数据:

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)

Run Code Online (Sandbox Code Playgroud)

到目前为止,我已经这样做了:

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

但每个酒吧都没有标记城市名称。有任何想法吗?

Lat*_*row 5

回答

(归功于https://dmitrijskass.netlify.app/2019/06/30/multi-level-labels-with-ggplot2/

使用facet_grid

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

在此输入图像描述

更完整的版本

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
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述