[英]wanted: facet_grid - facet_wrap hybrid solution
我试图生成一个在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")
我知道为什么它不起作用,但我想知道是否有解决方法?
谢谢!
法比安
经过一番挖掘,我设法解决了这个问题。 从这里 (@ baptiste,@ Roland)和这里 (@Sandy Muspratt)借来的代码段。 看起来很吓人,但我基本上是通过低级操作从您的第一个情节中删除/重命名文本条。
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.