如何在X轴标签上删除组信息

时间:2018-10-09 20:37:23

标签: r ggplot2 boxplot

如果我使用ggplot正常绘制,我将依次获得x轴标签(图1)。我不希望按字母顺序排列,所以我使用交互。该图看起来与预期的一样,但是在x轴上显示的信息太多(图2)。是否有其他方法可以在不使用交互作用且x轴标签不按字母顺序排列的情况下进行绘制?谢谢。

enter image description here

             Figure 1

enter image description here

             Figure 2

我只想在x轴上显示“ item”,而不是“ type.item”。下面是简单的代码和数据。

    library("ggplot2")
    library("plyr")

    df<-data.frame(I = c(25, 25, 25, 25, 25, 85, 85, 85, 125, 125), 
           V =c(1.03, 1.06, 1.1,1.08,1.87,1.56,1.75,1.82, 1.85, 1.90), 
    type=c(2,2,2,2,2,2,2,2,2,2)) 

    df1<-data.frame(I = c(26, 26,26,86, 86, 86, 86, 126, 126,126), 
            V =c(1.13, 1.24,1.3,1.17, 1.66,1.76,1.89, 1.90, 1.95,1.97), 
    type=c(5,5,5,5,5,5,5,5,5,5)) 

    main <- rbind(df,df1) 
    main$type <- as.factor(main$type)
    main$I <- as.factor(main$I)

    main <- transform(main, type = revalue(type,c("2"="type2", 
    "5"="type5")))
    main <- transform(main, I = revalue(I,c("25"="item25", "85"="item85", 
    "125"="item125", "26"="item26", "86"="item86", "126"="item126")))

    main$I_type <- interaction(main$I,main$type) 
    ggplot(aes(y = V, x= I_type), data=main)+ 
    geom_boxplot(outlier.colour=NA,aes(color=type),size=.4, 
    position='identity',width= .3) + theme_bw() +
    theme(axis.text.x = element_text(angle = 90, hjust = 1))

1 个答案:

答案 0 :(得分:3)

您可以使用scale_x_discrete自定义轴标签。

main$I_type <- droplevels(main$I_type)

ggplot(aes(y = V, x = I_type), data = main) + 
  geom_boxplot(outlier.colour = NA, aes(color = type), size = 0.4, 
               position = 'identity', width = 0.3) + 
  scale_x_discrete(labels = sub("\\..*$", "", levels(main$I_type))) +
  theme_bw() +
  theme(axis.text.x = element_text(angle = 90, hjust = 1))

enter image description here

相关问题