R 如何从ggplot2面中删除空因子?
我试图通过根据因子变量引入面来修改绘图 假设此结构的数据:R 如何从ggplot2面中删除空因子?,r,ggplot2,R,Ggplot2,我试图通过根据因子变量引入面来修改绘图 假设此结构的数据: test <- structure(list(characteristic = structure(c(1L, 2L, 3L, 1L, 2L ), .Label = c("Factor1", "Factor2", "Factor3"), class = "factor"), es = c(1.2, 1.4, 1.6, 1.3, 1.5), ci_low = c(1.1, 1.3, 1.5, 1.2, 1.4),
test <- structure(list(characteristic = structure(c(1L, 2L, 3L, 1L, 2L
), .Label = c("Factor1", "Factor2", "Factor3"), class = "factor"),
es = c(1.2, 1.4, 1.6, 1.3, 1.5), ci_low = c(1.1, 1.3, 1.5,
1.2, 1.4), ci_upp = c(1.3, 1.5, 1.7, 1.4, 1.6), label = structure(c(1L,
3L, 5L, 2L, 4L), .Label = c("1.2 (1.1, 1.3)", "1.3 (1.2, 1.4)",
"1.4 (1.3, 1.5)", "1.5 (1.4, 1.6)", "1.6 (1.5, 1.7)"), class = "factor"),
set = structure(c(1L, 1L, 1L, 2L, 2L), .Label = c("H", "S"
), class = "factor")), .Names = c("characteristic", "es",
"ci_low", "ci_upp", "label", "set"), class = "data.frame", row.names = c(NA,
-5L))
测试使用scales=“free”
如下所示:
p <- ggplot(test, aes(x=characteristic, y=es, ymin=ci_low, ymax=ci_upp)) + geom_pointrange() +
coord_flip() + geom_hline(aes(x=0), lty=2) +
facet_wrap(~ set, ncol = 1, scales="free") +
theme_bw() +
opts(strip.text.x = theme_text())
p
编辑更新为ggplot2 0.9.3
这是另一个解决方案。它使用facet_网格
和space=“free”
;它还使用geom_point()
和geom_errorbarh()
,因此不需要coord.flip()
。此外,x轴记号标记标签仅显示在下部面板上。在下面的代码中,主题
命令不是必需的-它用于旋转条形文本以水平显示。使用上面的测试
数据帧,以下代码应该产生您想要的结果:
library(ggplot2)
p <- ggplot(test, aes(y = characteristic, x = es, xmin = ci_low, xmax = ci_upp)) +
geom_point() +
geom_errorbarh(height = 0) +
facet_grid(set ~ ., scales = "free", space = "free") +
theme_bw() +
theme(strip.text.y = element_text(angle = 0))
p
库(ggplot2)
p在引用R时,我不再问“是否有…”,而是开始问“我如何才能…”,install.packages(“fortunes”);图书馆(财富);《财富》(“尤达”)
太棒了!这是一种魅力。但有一个问题:面板的大小是否总是成比例的(垂直)?有。。不是-我如何根据每个人使用的因素数量来衡量它们?例如,如果我在上面板中有10个,在下面板中有3个,我认为space=“free”
是您要寻找的另一个参数。但是scales='free_x'
在那里不再起作用了:/out如何使轴的比例不扩大?在本例中,请注意因子1和因子2网格线之间的空间在顶部和底部之间是不同的。这里不太明显,但在创建堆叠条形图时,条形图的宽度在镶嵌面面板之间会有很大的不同,这取决于轴中被丢弃的因子的数量。这件事把我难住了。有什么想法吗?只是一个音符,drop=TRUE对我不起作用,scales=TRUE对我起作用。可能与我的代码的某些细节有关。
p <- ggplot(test, aes(x=characteristic, y=es, ymin=ci_low, ymax=ci_upp)) +
geom_pointrange() +
coord_flip() + geom_hline(aes(x=0), lty=2) +
facet_wrap(~ set, ncol = 1, drop=TRUE) +
theme_bw() +
opts(strip.text.x = theme_text())
p
library(ggplot2)
p <- ggplot(test, aes(y = characteristic, x = es, xmin = ci_low, xmax = ci_upp)) +
geom_point() +
geom_errorbarh(height = 0) +
facet_grid(set ~ ., scales = "free", space = "free") +
theme_bw() +
theme(strip.text.y = element_text(angle = 0))
p