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

时光怂恿深爱的人放手 提交于 2019-12-25 05:14:14

问题


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/



来源:https://stackoverflow.com/questions/42216352/how-to-change-the-order-of-x-axis-in-multiple-boxplots-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!