How to change the order of x-axis in multiple boxp

2019-09-14 01:04发布

问题:

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!

回答1:

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/