1

If I plot normally with ggplot, I will have x axis labels in order (figure 1). I don't want the alphabetical order, so I use interaction. The plot looks as expected, but there is too much information to show on x axis (figure 2). Is there other way to plot without using interaction and x axis label not alphabetical order ? Thank you.

enter image description here

             Figure 1

enter image description here

             Figure 2

I want to show on x axis "item" only instead of "type.item". Below is the simple code and data.

    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))
Peter Rowan
  • 127
  • 1
  • 11
  • You may want to consider using `facets` instead: `ggplot(main, aes(x = I, y = V, color = type)) + geom_boxplot() + facet_wrap(~ type, scales = "free_x")` – JasonAizkalns Oct 09 '18 at 20:47
  • @JasonAizkalns, I have tried as you suggested, it didn't work and I had an error "Error: 'predicate' must be a closure or function pointer". I don't know what is an issue. Thank you. – Peter Rowan Oct 09 '18 at 20:54

1 Answers1

4

You can use scale_x_discrete to customize your axis labels.

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

Rui Barradas
  • 70,273
  • 8
  • 34
  • 66