ggplot2 facet_grid在y轴上创建面板

时间:2018-11-06 15:50:52

标签: r ggplot2 yaxis facet-grid

我有类似以下示例的数据:

public static <X, Y, Z> SortedMap<X, Z> transformValues(Map<? extends X, ? extends Y> input, Function<Y, Z> function) {
    return input.keySet()
                .stream()
                .collect(Collectors.toMap(Function.identity(),
                                          key -> function.apply(input.get(key)),
                                          (v1, v2) -> {
                                              return v1;
                                          }, TreeMap::new));

}

我的代码是:

dat1 <- data.frame(group=c("a", "a","a", "a","a","a","b","b","b","b","b", "b", "b","b","b","c","c","c","c","c","c"),
                   subgroup=c(paste0("R", rep(1:6)),paste0("R", rep(1:9)),paste0("R", rep(1:6))),
                   value=c(15,16,12,12,14,5,14,27,20,23,14,10,20,22,14,15,18,14,23,30,32),
                   pp=c("AT","BT","CT","AA","CC","SE","DN","AS","MM","XT","QQ","HH","MK","HT","dd","US","AG","TT","ZZ","XK","RU"),
                   clusters=c(rep("cluster1",6),rep("cluster2",9),rep("cluster3",6)))

colors <- c(rep("#74c1e8",6),rep("#808000",9),rep("#FF69B4",6))
names(colors) <- c("cluster1","cluster2","cluster3")

enter image description here

我想要的是在每个群集之后在y_axis上添加一些空间。例如,在群集3(红色)之后,我想在下图中添加一些空间,例如面板之间的空间,等等。

enter image description here 有没有办法做到这一点?

1 个答案:

答案 0 :(得分:4)

我的解决方案将y轴转换为一个因子,并在每个聚类之间添加geom_hline

library(tidyverse)
dat1 <- data.frame(group=c("a", "a","a", "a","a","a","b","b","b","b","b", "b", "b","b","b","c","c","c","c","c","c"),
                   subgroup=c(paste0("R", rep(1:6)),paste0("R", rep(1:9)),paste0("R", rep(1:6))),
                   value=c(15,16,12,12,14,5,14,27,20,23,14,10,20,22,14,15,18,14,23,30,32),
                   pp=c("AT","BT","CT","AA","CC","SE","DN","AS","MM","XT","QQ","HH","MK","HT","dd","US","AG","TT","ZZ","XK","RU"),
                   clusters=c(rep("cluster1",6),rep("cluster2",9),rep("cluster3",6)))

colors <- c(rep("#74c1e8",6),rep("#808000",9),rep("#FF69B4",6))
names(colors) <- c("cluster1","cluster2","cluster3")




ggplot(dat1, aes(y = factor(pp), x = subgroup)) + geom_point(aes(size=value)) + facet_grid(~group, scales="free_x", space  = "free")+ 
    ylab("names") + 
    xlab(" ") + 
    theme(axis.text.y = element_text(color=colors)) + 
  geom_hline(yintercept = 15.5, color = "white", size = 2) + 
  geom_hline(yintercept = 6.5, color = "white", size = 2)

enter image description here