代码之家  ›  专栏  ›  技术社区  ›  Herman Toothrot

ggplot2在镶嵌面面板中移动x轴标签

  •  -1
  • Herman Toothrot  · 技术社区  · 8 年前

    数据

    subj <- c(rep(11,3),rep(12,3),rep(14,3),rep(15,3),rep(17,3),rep(18,3),rep(20,3))
    group <- c(rep("u",3),rep("t",6),rep("u",6),rep("t",6))
    time <- rep(1:3,7)
    mean <- c(0.7352941, 0.8059701, 0.8823529, 0.9264706, 0.9852941, 0.9558824, 0.7941176, 0.8676471, 0.7910448, 0.7058824, 0.8382353, 0.7941176, 0.9411765, 0.9558824, 0.9852941, 0.7647059, 0.8088235, 0.7968750, 0.8088235, 0.8500000, 0.8412698)
    df <- data.frame(subj,group,time,mean)
    df$subj <- as.factor(df$subj)
    df$time <- as.factor(df$time)
    

    ggplot(df, aes(x=subj, y=mean*100, fill=time)) +
      geom_bar(stat="identity", position="dodge") +
      facet_wrap(~ group, scale="free")
    

    我只想在小平面面板上显示x轴标签号12、14等,它们应该像在x轴上一样对齐。

    否则,我将不得不移动顶部的x轴并移除面板。

    1 回复  |  直到 8 年前
        1
  •  3
  •   AndS.    8 年前

    所以我明白你的要求,你可以这么做,但是,这是非常武断的

    library(tidyverse)
    
    my_labs <- c(t = "12                14                18                20", 
                 u = "11                      15                      17")
    ggplot(df, aes(x=subj, y=mean*100, fill=time)) +
      geom_bar(stat="identity", position="dodge") +
      facet_wrap(~ group, scale="free", labeller = as_labeller(my_labs))
    

    geom_text 标记列,使其始终位于正确的位置。从长远来看,它们也会更好看。

    my_text <- data_frame(subj = as.factor(c(12,14,18,20,11,15,17)), group = c(rep("t", 4), rep("u", 3)), mean = c(rep(105, 7)))
    
    ggplot(df, aes(x=subj, y=mean*100, fill=time)) +
      geom_bar(stat="identity", position="dodge") +
      geom_text(data = my_text, aes(x=subj, y=mean, label = subj), inherit.aes = FALSE)+
      facet_wrap(~ group, scale="free")+
      theme(strip.background = element_blank(),
            strip.text = element_blank())
    

    df <- df %>% mutate(subj = factor(subj, levels = c("12", "14", "18", "20", "11", "15", "17")))
    my_labs <- levels(df$subj)
    ggplot(df, aes(x=as.numeric(subj), y=mean*100, fill=time)) +
      geom_bar(stat="identity", position="dodge") +
      facet_wrap(~ group, scale="free")+
      scale_x_continuous(breaks = 1:length(my_labs), labels = my_labs, sec.axis = dup_axis())+
      xlab("subj")+
      theme(strip.background = element_blank(),
            strip.text = element_blank())
    

    于2018年8月18日由 reprex package (第0.2.0版)。

    推荐文章