Reputation: 1970
Using the variables (day, month, count) in the data frame d, I use ggplot below:
day <- c("Mon","Tues","Wed","Thurs","Fri","Sat","Sun","Week","Mon","Tues","Wed","Thurs","Fri","Sat","Sun","Week")
day <- factor(day, level=c("Mon","Tues","Wed","Thurs","Fri","Sat","Sun","Week"))
month<-c("Jan","Jan","Jan","Jan","Jan","Jan","Jan","Jan","Feb","Feb","Feb","Feb","Feb","Feb","Feb","Feb")
month<-factor(month,level=c("Jan","Feb"))
count <- c(4,5,6,8,3,4,9,5.57,2,4,3,7,1,9,3,4.14)
d <- data.frame(day=day,count=count,month=month)
d
The line graph below correctly orders the days:
ggplot()+geom_line(data=d[d$day!="Week",],aes(x=day, y=count, group=month, colour=month))
The bar graph below correctly displays the two counts:
ggplot()+geom_bar(data=d[d$day=="Week",],aes(x=day, y=count, fill=month),position="dodge")
However, the order of days is incorrect in the combined graph:
ggplot()+geom_line(data=d[d$day!="Week",],aes(x=day, y=count, group=month, colour=month))+geom_bar(data=d[d$day=="Week",],aes(x=day, y=count, fill=month),position="dodge")
How can I correctly display the order of days on the x-axis?
Upvotes: 1
Views: 867
Reputation: 98509
You can use scale_x_discrete()
to change order of breaks with argument limits=
. As in your original data frame factor levels are in right order then you can just use limits=levels(d$day)
.
ggplot()+
geom_line(data=d[d$day!="Week",],
aes(x=day, y=count, group=month, colour=month))+
geom_bar(data=d[d$day=="Week",],
aes(x=day, y=count, fill=month),position="dodge")+
scale_x_discrete(limits=levels(d$day))
Upvotes: 3