问题
I would like to make a boxplot that shows how time spent doing a behaviour(Alert) is affected by two variables (Period= Morning/Afternoon and Visitor Level= High/Low).
Alert ~ Period + Vis.Level
'Alert' is a set of 12 numbers that show the amount of time spent awake with the other two as the significant categorical variables. I have looked at other examples but none seem to fit this type of question.
I know the graph I am looking for would have 4 boxplots on it... supposedly with
- PeriodMorning+Vis.LevelHigh
- PeriodMorning+Vis.LevelLow
- PeriodAfternoon+Vis.LevelHigh
- PeriodAfternoon+Vis.LevelLow
on the x axis.
Any help at all would be fantastic!
Alert Vis.Level Period
1 0.0 Low Morning
2 1.0 Low Morning
3 0.0 Low Morning
4 11.5 Low Afternoon
5 6.0 Low Afternoon
6 11.5 Low Afternoon
7 0.0 High Morning
8 0.0 High Morning
9 0.0 High Morning
10 0.0 High Afternoon
11 2.5 High Afternoon
12 7.5 High Afternoon
回答1:
Assuming your data looks like this
dd <- structure(list(Alert = c(0, 1, 0, 11.5, 6, 11.5, 0, 0, 0, 0,
2.5, 7.5), Vis.Level = c("Low", "Low", "Low", "Low", "Low", "Low",
"High", "High", "High", "High", "High", "High"), Period = c("Morning",
"Morning", "Morning", "Afternoon", "Afternoon", "Afternoon",
"Morning", "Morning", "Morning", "Afternoon", "Afternoon", "Afternoon"
)), .Names = c("Alert", "Vis.Level", "Period"), class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"))
Then you'll want to make sure your factors are in the correct order
dd$Period<-factor(dd$Period, levels=c("Morning","Afternoon"))
dd$Vis.Level<-factor(dd$Vis.Level, levels=c("Low","High"))
Then you can do
boxplot(Alert~Period+Vis.Level, dd)
or you can get the exact layout you requested with
boxplot(Alert~interaction(Period, Vis.Level, lex.order=T), dd)

来源:https://stackoverflow.com/questions/25369870/how-do-i-make-a-boxplot-with-two-categorical-variables-in-r