简体   繁体   中英

wanted: facet_grid - facet_wrap hybrid solution

I am trying to produce a plot with a sort of "hybrid" layout between facet_grid and facet_wrap:

example:

library(reshape2)
library(ggplot2)

data(diamonds)

# sample and reshape diamond dataset
diamonds_l <- melt(diamonds[sample(1:nrow(diamonds), 200), 
                            c("cut", "depth", "table", "price", "x")],
                   id.vars = c("cut","x"))

this is the plot arrangement that I want (quality in columns and depth, table, price as rows)

ggplot( diamonds_l, aes( x = value, y = x, colour= cut))+
  geom_point( ) +
  facet_wrap( variable ~  cut, scales = "free_x", nrow=3) 

在此处输入图片说明

however, I would prefer the facet_grid design (only one header per column / row) but scales = "free_x" doesn't work in this layout

ggplot( diamonds_l, aes( x = value, y = x, colour= cut))+
  geom_point( ) +
  facet_grid(variable ~  cut, scales = "free_x") 

在此处输入图片说明

it works here but thats not the arrangement that I want (quality as rows)

ggplot( diamonds_l, aes( x = value, y = x, colour= cut))+
  geom_point( ) +
  facet_grid(cut ~ variable, scales = "free_x")

在此处输入图片说明

I understand why it won't work but I was wondering if there was a work-around?

thanks!

Fabian

After some digging, I managed to pull the trick. Pieces of code borrowed from here (@baptiste, @Roland) and here (@Sandy Muspratt). Looks scary, but I'm basically removing/renaming text strips from the first plot of yours via low-level manipulations.

p <- ggplot( diamonds_l, aes( x = value, y = x, colour= cut))+
  geom_point( ) +
  facet_wrap( variable ~ cut, scales = "free_x", nrow = 3) 

library(gridExtra)
gt <- ggplotGrob(p)
panels <- grep("panel", gt$layout$name)
top <- unique(gt$layout$t[panels])
gt <- gt[-(top[-1]-1), ]

gg <- gt$grobs      
strips <- grep("strip_t", names(gg))
labels <- levels(diamonds_l$cut)
for(ii in seq_along(labels))  {
  modgrob <- getGrob(gg[[strips[ii]]], "strip.text", 
                     grep=TRUE, global=TRUE)
  gg[[strips[ii]]]$children[[modgrob$name]] <- editGrob(modgrob,label=labels[ii])
}
gt$grobs <- gg
grid.newpage()
grid.draw(gt)

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM