简体   繁体   中英

How to change the order of x-axis in multiple boxplots in R

I am trying to change the order x-axis in this boxplot.

[Now the order is loupe, microscope and video, and I want to change it to microscope, loupe then video]

The dataframe example is like this

 Label      Mental Physical Temporal Performance Effort Frustration sum
 Microscope  10     10      10       10     10      10    60
 Microscope  10     10      10       10     10      10    60
 Loupe       20     20      20       20     20      20    120 
 Loupe       20     20      20       20     20      20    120 
 Video       15     15      15       20     20      20    105 
 Video       15     15      15       20     20      20    105 

This is boxplot i have right now boxplot1

This is my code for ggplot

  mydata <- read.csv("boxplotyiyu2.csv",header=TRUE)
  dfm <- melt(mydata, id.var = "Label")
  ggplot(data = dfm, aes(x=variable, y=value)) + geom_boxplot(aes(fill=Label),width=0.5)+ xlab("Demand") + ylab("NASA-TLX Scores")

And I have tried this, but the result is not correct.

dfm$variable <- factor(dfm$variable,levels = c("Microscope","Loupe","Video"))

Another question is how to modify the y-axis for multiple boxplots. I have this seven boxplots together, but i want to change the y-axis for each small plot. boxplot2

(The dataframe is similar with above one, just replace mental,physical...with angle data)

The code I have is

  df.m <- melt(mydata, id.var = "Label")
  p <- ggplot(data = df.m, aes(x=variable, y=value))
  p <- p + geom_boxplot(aes(fill=Label))
  p <- p + facet_wrap( ~ variable, scales="free")
  p <- p + xlab("Angle") + ylab("Degree")

Please do me a favor! Really appreciate it!

You will need to redefine the order of the factors with the factor function.

#Sample data
Label<-c("Microscope", "Microscope", "Loupe", "Loupe", "Video", "Video")
mydata<-data.frame(Label)

#print out
levels(mydata$Label)

mydata$Label<-factor(mydata$Label, levels=c("Microscope", "Loupe",  "Video"))
#print out
levels(mydata$Label)

See the cookbook-r.com for more information: http://www.cookbook-r.com/Manipulating_data/Changing_the_order_of_levels_of_a_factor/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM