我试图在facet_grid和facet_wrap之间生成一个具有某种“混合”布局的情节:
示例:
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"))这是我想要的地块安排(质量在栏和深度,表,价格作为行)
ggplot( diamonds_l, aes( x = value, y = x, colour= cut))+
geom_point( ) +
facet_wrap( variable ~ cut, scales = "free_x", nrow=3)

但是,我更喜欢facet_grid设计(每列/行只有一个标头),但是scales = "free_x“在这个布局中不起作用
ggplot( diamonds_l, aes( x = value, y = x, colour= cut))+
geom_point( ) +
facet_grid(variable ~ cut, scales = "free_x")

它在这里工作,但这不是我想要的安排(行的质量)。
ggplot( diamonds_l, aes( x = value, y = x, colour= cut))+
geom_point( ) +
facet_grid(cut ~ variable, scales = "free_x")

我明白它为什么行不通,但我想知道是否有一个解决办法?
谢谢!
法比安
发布于 2015-06-24 12:12:29
经过一番挖掘,我终于成功了。从here (@巴普蒂斯特,@Roland)和here (@Sandy )借用的代码片段。看起来很可怕,但我基本上是通过低级操作从你的第一个情节中删除/重命名文本条。
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)

https://stackoverflow.com/questions/31023662
复制相似问题