【发布时间】:2021-08-04 22:45:55
【问题描述】:
这是来自geom_boxplot man page 的示例:
p = ggplot(mpg, aes(class, hwy))
p + geom_boxplot(aes(colour = drv))
看起来像这样:
我想制作一个非常相似的图,但使用(yearmon 格式化)日期,class 变量在示例中,而因子变量drv 在示例中。
这里是一些示例数据:
df_box = data_frame(
Date = sample(
as.yearmon(seq.Date(from = as.Date("2013-01-01"), to = as.Date("2016-08-01"), by = "month")),
size = 10000,
replace = TRUE
),
Source = sample(c("Inside", "Outside"), size = 10000, replace = TRUE),
Value = rnorm(10000)
)
我尝试了很多不同的东西:
-
在日期变量周围放置一个
as.factor,然后我不再有 x 轴的间隔很好的日期刻度:df_box %>% ggplot(aes( x = as.factor(Date), y = Value, # group = Date, color = Source )) + geom_boxplot(outlier.shape = NA) + theme_bw() + xlab("Month Year") + theme( axis.text.x = element_text(hjust = 1, angle = 50) )
-
另一方面,如果我按照建议的here 将
Date用作附加的group变量,则添加color不再有任何附加影响:df_box %>% ggplot(aes( x = Date, y = Value, group = Date, color = Source )) + geom_boxplot() + theme_bw()
关于如何在保持yearmon 缩放 x 轴的同时实现 #1 的输出的任何想法?
【问题讨论】:
-
您可以使用刻面而不是颜色,例如
ggplot(df_box, aes(x = Date, y = Value, group = factor(Date))) + geom_boxplot() + facet_wrap(~Source) -
@alistaire 感谢您的建议。我确实尝试过,但是当它们并排时比较分布是最容易的,尤其是当要比较的组件与箱线图中的组件一样多时。
-
如果您愿意,可以使用
facet_grid垂直切面。不过,我想出了如何按照您的方式进行操作,方法是使用Source和Date的交互作为group美学:ggplot(df_box, aes(x = Date, y = Value, colour = Source, group = interaction(Source, Date))) + geom_boxplot()