ggplot facet_grid panel.spacing w / axis label position =" right"

时间:2018-05-23 23:07:06

标签: r ggplot2

我在xy轴上创建了一个带有刻面的热图/平铺图,由于某种原因,面板标签的间距与正确的间距不匹配数据面板。

这是示例数据和图表。

library(data.table)
td = data.table(Sym=rep(paste0("sym",1:14),141),
                sample=rep(paste0("sample",1:141), 14),
                value = sample(x=0:100, size=141*14,replace=T)/100,
                group = rep(c(rep(1,12),rep(2,34),rep(3,28),rep(4,27),rep(5,40)),14)
           )
td[, category := ifelse(Sym %in% paste0("sym",1:5), "cat1",
                        ifelse(Sym %in% paste0("sym",6:10), "cat2",
                               ifelse(Sym %in% paste0("sym",11:14), "cat3",NA)))]

p = ggplot(td, 
       aes(x=sample,y=Sym, fill=value))+
  geom_tile()+
  facet_grid(category ~ group,scales = "free",space = "free", switch = "y")+
  scale_y_discrete(position = "right")+
  theme(axis.title = element_blank(),
        axis.ticks = element_blank(),
        axis.text.x = element_blank(),
        axis.line = element_blank(),
        strip.text.y = element_text(angle=180),
        strip.text.x = element_text(color="white"))
p

unequal facets

注意y轴刻面与数据的tileplot不完全对齐。我试图更改主题中的面板间距,问题仍然存在:

p+theme(panel.spacing = unit(0,"lines"))

after changing panel spacing

最后,我可以通过重置y轴刻度来修复它:

p+scale_y_discrete(position="right", expand = c(0,0))

enter image description here

看起来这是由于我使用scale_y_discrete(position="right")将y轴标签设置在绘图的右侧。有没有更好的方法来设置y轴标签在右侧绘制而不影响刻面间距?

0 个答案:

没有答案