R ggplot:将轴和构面标签对齐到相同的高度

时间:2019-04-29 09:31:35

标签: r ggplot2

我已经使用ggplot2软件包进行了绘制。我想使小平面的标签和每个小平面的第一个轴标签在相同的高度上。 (例如,B和1,本例中的C和7,一行)

现在1和7略低于B和C。

enter image description here

除了丢下刻面并制作自定义轴标签以外,还有其他解决方案吗?我想保留这些方面以便进行布局。

这是可复制的示例代码:

tst <- structure(list(cat = c("A", "B", "C", "C", "C", "C", "C", "C", "C"), 
                      value = c("", "1", "1", "2", "3", "4", "5", "6", "7"), 
                      estimate = c(-0.0426199922176837, -0.107596434933479, 
                                   0.128745430017863, 0.139050280246278, 0.083438545558878, 0.0353561915958545, 
                                   0.546763649283651, -0.149906486541816, -0.0127866090227199), 
                      lo = c(-0.0463977305439748, -0.13825456791009, 0.0431405496176399, 
                             0.0510334567045194, 0.0149123471502507, -0.0170404544157982, 
                             0.495233535388663, -0.220062569612812, -0.0648067498492498), 
                      hi = c(-0.0388422538913925, -0.0769383019568673, 0.214350310418086, 
                             0.227067103788036, 0.151964743967505, 0.0877528376075072, 
                             0.598293763178639, -0.0797504034708195, 0.03923353180381)), 
                 row.names = c(NA, -9L), 
                 class = c("tbl_df", "tbl", "data.frame"))

ggplot(data=tst,
       aes(x = value,y = as.numeric(estimate), ymin = lo, ymax = hi )) +
  geom_point() +
  xlab('') + ylab("Effect size (95% Confidence Interval)") +
  geom_errorbar(aes(ymin=lo, ymax=hi)) + 
  facet_grid(cat~.,
             scales = "free_y",
             space = "free_y",
             switch = "y"
  ) +
  theme(strip.text.y = element_text(hjust=0,vjust = 1,angle=180,face="bold"),
        strip.placement = "outside",
        panel.spacing = unit(-0.5, "lines"),
        strip.background = element_blank()) +
  coord_flip()

1 个答案:

答案 0 :(得分:0)

我只看到一种制作自定义轴标签的方法,例如

library(tidyverse)
tst %>% 
 mutate(id = ifelse(value < 7 & cat == "C", "", cat)) %>% 
 mutate(id = factor(id, level=c("A", "B", "C", ""))) %>% 
    ggplot(aes(x = value,y = as.numeric(estimate), ymin = lo, ymax = hi )) +
 geom_point() +
  facet_grid(id~.,
             scales = "free_y",
             space = "free_y",
             switch = "y") +
 xlab('') + ylab("Effect size (95% Confidence Interval)") +
 geom_errorbar(aes(ymin=lo, ymax=hi)) + 
  coord_flip()+
  theme(strip.placement = "outside",
        strip.text.y = element_text(angle=180, face="bold"),
        panel.spacing = unit(-0.5, "lines"),
        strip.background = element_blank())

enter image description here