0

I want to remove the whole panel from ggplot 2-way facet_grid. I have taken some lead from this question. Here is the code with example data

library(ggplot2)
library(ggh4x)

df <- data.frame(x=rnorm(80),y=rnorm(80),
                  col=rep(c(" ", "B","C"," ","B","C","B","C"),each=10),
                  row=rep(c("a","a","a","b","b","b","c","c"),each=10))

ggplot(data=df,aes(x=x,y=y))+
  geom_point()+
  facet_grid2(row~col, scales = "free", independent = "all")

enter image description here

I want to remove the left panel. How can it be done?

UseR10085
  • 7,120
  • 3
  • 24
  • 54

2 Answers2

3

Noted from your comment that subsetting the dataset beforehand isn't an option for you, so here's a post-production approach:

# create plot
p <- ggplot(data=df,aes(x=x,y=y))+
  geom_point()+
  facet_grid2(row~col, scales = "free", independent = "all")

# convert to grob
gp <- ggplotGrob(p)

# check which are the columns of the gtable to strip out
# (for the example, we want to strip out content from cols 4-5)
gp                             # examine layout in console
gtable::gtable_show_layout(gp) # examine layout in viewer

# strip them out
gp <- gp %>%
  cowplot::gtable_remove_grobs(names = gp$layout %>% 
                                 filter(r %in% 4:5) %>% 
                                 pull(name)) %>%
  cowplot::gtable_squash_cols(cols = 4:5)

# plot the result
plot(gp)

result

data:

set.seed(123)
df <- data.frame(x=rnorm(80),y=rnorm(80),
                 col=rep(c(" ", "B","C"," ","B","C","B","C"),each=10),
                 row=rep(c("a","a","a","b","b","b","c","c"),each=10))
Z.Lin
  • 28,055
  • 6
  • 54
  • 94
  • It will be great if you can explain how have you selected `4:5` i.e `gtable_show_layout`? – UseR10085 May 13 '23 at 14:18
  • It takes some familiarity with the typical way a ggplot2 object is laid out in a table of grobs, but the basic idea is that you can compare the plot appearance with the underlying tabular structure, & recognize columns 4-5 contain the y-axis labels + plot panels of the first facet column. – Z.Lin May 13 '23 at 14:38
2

One way is to use subset():

library(ggplot2)
library(ggh4x)

df %>%
  subset(!(row == "a" & col == " ")) %>%
  ggplot(aes(x=x,y=y)) +
  geom_point() +
  facet_grid2(row~col, scales = "free", independent = "all")

enter image description here

TarJae
  • 72,363
  • 6
  • 19
  • 66
  • 1
    Rather than subsetting can we have a graphical way to do it like [this](https://stackoverflow.com/a/49525552/6123824)? For my original dataset subset is not working. – UseR10085 May 13 '23 at 09:36