Reputation: 2666
Say I have a dataframe, test
:
d1<-c(4.1,4.9,4.5,4.4,1.9,2.1,2.3,1.7,10.1,9.5,10.9,10.3,3.1,3.0,3.2,2.9)
d2<-c('a','a','a','a','b','b','b','b','c','c','c','c','d','d','d','d')
d3<-c(0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1)
test<-data.frame(d1,d2,d3)
if I make boxplots as a function of d2, I get the following figure:
plot(d1~d2,data=test)
However, I would like to change two things about this plot:
(1) I want it to plot the two observations with the value of 0
in d3
to plot first, and those with the value 1
to plot second.
(2) I want it to order the observations within each of these groups by the magnitude of the y value.
The correct final order would be a, c, b, d.
Bonus if you can add colors based on the d3
variable.
Upvotes: 1
Views: 306
Reputation: 83225
If I understand you coorectly, you can do this with ggplot2
:
library(ggplot2)
ggplot(test, aes(x=reorder(d2,d3), y=d1, fill=factor(d3))) +
geom_boxplot()
this gives:
You can do the same tric in base R:
plot(d1~reorder(d2,d3),data=test)
Upvotes: 1