1

I am trying to create a dodged boxplot without using facet_wrap as facet_wrap alters the appearance from my requirement. I have a dataframe with three variables - time, week_num and region

dput(df)
structure(list(time = c(2657L, 2319L, 2324L, 2348L, 2134L, 2251L, 
1848L, 1816L, 1893L, 2177L, 3387L, 2329L, 6964L, 2162L, 6682L, 
2268L, 5419L, 2088L, 3758L, 3021L, 2833L, 2950L, 4554L, 1213L, 
2085L, 1529L, 821L, 2406L, 2008L, 1264L, 2186L, 1654L, 1757L, 
2116L, 1876L, 2088L, 1900L, 2767L, 3051L, 1762L, 1499L, 1157L, 
1529L, 1396L, 1278L, 3367L, 1647L, 4393L, 2358L, 1535L, 2469L, 
2068L, 505L, 335L, 410L, 1159L), region = structure(c(1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 
2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 
3L, 3L, 3L, 3L, 3L, 3L), .Label = c("A", "B", "C"), class = "factor"), 
week_num = c(20L, 22L, 20L, 21L, 21L, 21L, 21L, 21L, 21L, 
21L, 21L, 21L, 21L, 21L, 22L, 22L, 22L, 22L, 22L, 22L, 22L, 
22L, 22L, 20L, 22L, 22L, 22L, 21L, 22L, 22L, 21L, 22L, 22L, 
21L, 19L, 19L, 22L, 18L, 20L, 21L, 21L, 21L, 21L, 21L, 21L, 
22L, 22L, 18L, 22L, 22L, 21L, 21L, 22L, 22L, 22L, 22L)), .Names = c("time", 
"region", "week_num"), row.names = c(NA, -56L), class = "data.frame")

I need a dodged box plot for each region corresponding to each week_num. The code I have implemented is like this.

plot_df= ggplot(data=df)+geom_boxplot(aes(x=week_num,y=time,group=week_num,fill=region),position =position_dodge(width=1))

The plot i am obtaining is like this.

boxplot output

The fill values are not coming correctly and dodging is also not happening. For the values of x which has multiple region values, the color appears to be gray. Any way to solve the problem?

Tony Rajan
  • 130
  • 1
  • 11
  • You should paste the output of the `summary(df)` call, not a picture (indent each line of said output it with 4 spaces). We also don't have your data it's unlikely aid will be forthcoming any time soon. Please read this: http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example and modify your post as needed. – hrbrmstr Jun 09 '16 at 10:28
  • Thank you for the suggestion. I have edited the post with reproducible data – Tony Rajan Jun 09 '16 at 12:21
  • I will take care of it in the future questions. Thank you. – Tony Rajan Jun 09 '16 at 13:17

1 Answers1

0

The problem is that your week_num variable is not a factor, though you want to form your groups according to it.

The following simple line of code should achieve your desired result. (Or just change your version by adding factor() around week_num.)

ggplot(df, aes(y = time, x = factor(week_num), fill = region)) + geom_boxplot()
janosdivenyi
  • 3,136
  • 2
  • 24
  • 36