使用ggplot在R中躲避箱图

时间:2016-06-09 09:31:58

标签: r ggplot2 boxplot

我正在尝试创建一个不使用facet_wrap的躲闪箱图,因为facet_wrap会改变我的要求。 我有一个包含三个变量的数据框 - time,week_num和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")

我需要为每个week_num对应的每个区域提供一个躲闪的箱形图。我实现的代码是这样的。

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

我获得的情节是这样的。

boxplot output

填充值未正确显示,也没有发生躲闪。对于具有多个区域值的x的值,颜色看起来是灰色的。有什么方法可以解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

问题是您的week_num变量不是一个因素,但您希望根据它来形成您的组。

以下简单的代码行应该可以达到您想要的效果。 (或者只是在factor()附近添加week_num来更改您的版本。)

ggplot(df, aes(y = time, x = factor(week_num), fill = region)) + geom_boxplot()