首页 > 解决方案 > 如何删除 x 轴标签上的组信息

问题描述

如果我用 ggplot 正常绘图,我将按顺序排列 x 轴标签(图 1)。我不想要字母顺序,所以我使用交互。该图看起来符合预期,但在 x 轴上显示的信息太多(图 2)。是否有其他方法可以在不使用交互和 x 轴标签而不是字母顺序的情况下进行绘图?谢谢你。

在此处输入图像描述

             Figure 1

在此处输入图像描述

             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))

标签: rggplot2boxplot

解决方案


您可以使用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))

在此处输入图像描述


推荐阅读