当仅按一个变量着色时,两个分组变量的单独框
Separate boxes for two grouping variables when color by only one variable
这是来自 geom_boxplot
man page 的示例:
p = ggplot(mpg, aes(class, hwy))
p + geom_boxplot(aes(colour = drv))
看起来像这样:
我想制作一个非常相似的图,但是示例中 class
变量所在的(yearmon
格式)日期,以及 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 的输出有什么想法吗?
由于 Date
和 Source
的每个组合都需要单独的框,因此请使用 interaction(Source, Date)
作为 group
美学:
ggplot(df_box, aes(x = Date, y = Value,
colour = Source,
group = interaction(Source, Date))) +
geom_boxplot()
这是来自 geom_boxplot
man page 的示例:
p = ggplot(mpg, aes(class, hwy))
p + geom_boxplot(aes(colour = drv))
看起来像这样:
我想制作一个非常相似的图,但是示例中 class
变量所在的(yearmon
格式)日期,以及 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 的输出有什么想法吗?
由于 Date
和 Source
的每个组合都需要单独的框,因此请使用 interaction(Source, Date)
作为 group
美学:
ggplot(df_box, aes(x = Date, y = Value,
colour = Source,
group = interaction(Source, Date))) +
geom_boxplot()