如何在 R 中使用 ggplot 根据条件创建 Facet Grid?

How to create Facet Grid based on condition using ggplot in R?

这个问题是 的延伸。基本上,我正在尝试使用以下代码根据位置在方面绘制系统的频率分布。当前的问题是我能够在绘图上绘制频率,但 x 轴显示了 Loc1 中的所有系统,这是错误的,因为 Loc1 仅包含 Sys1 和 Sys2。我的问题是有没有办法根据位置 modify/update x 轴?所以对于 Loc1,只会显示 "Sys1" 和 "Sys2" 的频率计数。对于 "Loc2",它将是 "Sys3"、"Sys4",而对于 "Loc3",它将仅为 "Sys6"。

提供代码说明

数据集

structure(list(Systems = c("Sys1", "Sys2", "Sys3", "Sys4", "Sys6"
), Locations = c("loc1", "loc1", "loc2", "loc2", "loc3"), frequency = c(2L, 
1L, 1L, 1L, 0L)), row.names = c(NA, -5L), class = "data.frame")

绘图代码

ggplot(d,aes(Systems,frequency))+geom_col()+facet_grid(.~Locations)

根据?facet_grid

scales - Are scales shared across all facets (the default, "fixed"), or do they vary across rows ("free_x"), columns ("free_y"), or both rows and columns ("free")?

space - If "fixed", the default, all panels have the same size. If "free_y" their height will be proportional to the length of the y scale; if "free_x" their width will be proportional to the length of the x scale; or if "free" both height and width will vary. This setting has no effect unless the appropriate scales also vary.

因此,我们可以将scalesspace的默认选项从"fixed"更改为"free_x" facet_grid

library(ggplot2) 
ggplot(d, aes(Systems,frequency)) +
      geom_col()+
      facet_grid(.~Locations, space= "free_x", scales = "free_x")