r - R中的ggplot2:一些变量有多个分组
问题描述
我正在尝试绘制优势比,但遇到了一个问题,因为我的一些变量不止一组。例如,CatA 和 CatC 有一个组(“S1”),但 CatB 和 CatD 有两个组(“S1”和“S2”)。
dfex = data.frame(stringsAsFactors=FALSE,
Category = c("CatA", "CatB", "CatB", "CatC", "CatD", "CatD"),
Grouping = c("S1", "S1", "S2", "S1", "S1", "S1"),
Odds = c(2.4, 3, 2.6, 2.4, 2.4, 1.7),
CILow = c(1.3, 1.2, 1.1, 1.2, 1.1, 0.8),
CIHigh = c(4.5, 4.6, 7.9, 5, 5.9, 3.7)
)
ggplot(dfex, aes(x = Odds, y = Category)) +
geom_vline(aes(xintercept = 1), size = .25, linetype = 'dashed') +
geom_errorbarh(aes(xmax = CIHigh, xmin = CILow), size = .5, height =
.2, color = 'gray50') +
geom_point(size = 3.5) +
theme(panel.grid.minor = element_blank()) +
scale_x_continuous(breaks = seq(0,7,1) ) +
coord_trans(x = 'log10') +
ylab('') +
xlab('Odds ratio')
我正在寻找一种包含 Grouping 变量的方法,以便出现名称(“S1”或“S2”),并且 CatB 和 CatD 中的不同组稍微偏移,以便您可以看到两者。
不太重要的是,是否有一种简单的方法可以让 CatA 位于顶部,以匹配数据框的顺序,而不为因子设置新的顺序?
解决方案
一种可能的做法是“刻面”你的情节:
ggplot(dfex, aes(x = Odds, y = Grouping))+
geom_errorbarh(aes(xmax = CIHigh, xmin = CILow), size = .5, height =
.2, color = 'gray50') +
geom_point(size = 3.5) +
theme(panel.grid.minor = element_blank()) +
scale_x_continuous(breaks = seq(0,7,1) ) +
coord_trans(x = 'log10') +
ylab('') +
xlab('Odds ratio')+
facet_grid(Category~., switch = "y", scales = "free_y")+
theme(strip.placement = "outside",
strip.text.y = element_text(angle = 180),
strip.background.y = element_blank(),
panel.spacing = unit(-1, "lines"))
另一种解决方案是使用和interaction
对 y 值进行分组。Category
Grouping
reorder
如果您不想在使用之前重新排序因子,也可以在每个函数中传递函数ggplot
:
ggplot(dfex, aes(x = Odds,
y = interaction( reorder(Category, desc(Category)), reorder(Grouping,desc(Grouping)))))+
geom_vline(aes(xintercept = 1), size = .25, linetype = 'dashed') +
geom_errorbarh(aes(xmax = CIHigh, xmin = CILow), size = .5, height =
.2, color = 'gray50') +
geom_point(size = 3.5) +
theme(panel.grid.minor = element_blank()) +
scale_x_continuous(breaks = seq(0,7,1) ) +
coord_trans(x = 'log10') +
ylab('') +
xlab('Odds ratio')
它回答了你的问题吗?
更新到ggplot2
v3.3.0
使第一个解决方案工作ggplot2
v3.3.0 的小调整是替换:
strip.text.y = element_text(angle = 180),
和
strip.text.y.left = element_text(angle = 0),
推荐阅读
- python - 使用 Python 创建功能数据透视表
- r - 按 r 中最早的日期和 id 的条件
- spatstat - 如何拟合Geyer饱和过程以进行标记之间的交互?
- asp.net-mvc - Safari Mojave 向另一个域发布请求会导致“对象已移至此处”。
- typescript - TypeScript 编译器 API 将 CompilerOptions 的默认/内置转换应用于 AST
- c++ - 按值传递参数时抛出的异常在哪里
- combobox - 访问组合框可以在列表中突出显示颜色吗?
- python - 当所有蜘蛛关闭时,Scrapy 会收到通知
- python - 如何在 PCA 期间保留类标签
- azure-powershell - PowerShell Az Analysis Services 合并分区 - 获取凭据错误