首页 > 解决方案 > 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 位于顶部,以匹配数据框的顺序,而不为因子设置新的顺序?

标签: rggplot2

解决方案


一种可能的做法是“刻面”你的情节:

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 值进行分组。CategoryGrouping

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')

在此处输入图像描述

它回答了你的问题吗?


更新到ggplot2v3.3.0

使第一个解决方案工作ggplot2v3.3.0 的小调整是替换:

strip.text.y = element_text(angle = 180),

strip.text.y.left = element_text(angle = 0),

推荐阅读