如何删除x轴标签上的组信息

问题描述 投票:1回答:1

如果我用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))
r ggplot2 boxplot
1个回答
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

© www.soinside.com 2019 - 2024. All rights reserved.