简体   繁体   中英

Dodged boxplot in R using ggplot

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?

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM