我需要在以下图形中添加一些局部箱形图:
library(tidyverse)
foo <- tibble(
time = 1:100,
group = sample(c("a", "b"), 100, replace = TRUE) %>% as.factor()
) %>%
group_by(group) %>%
mutate(value = rnorm(n()) + 10 * as.integer(group)) %>%
ungroup()
foo %>%
ggplot(aes(x = time, y = value, color = group)) +
geom_point() +
geom_smooth(se = FALSE)
我将在上面的图中添加一个(2 x 4 = 8)箱形图的网格(每组4个)。每个箱线图应考虑连续选择25个(或n个)点(在每个组中)。也就是说,前两个箱形图表示第1个和第25个箱形图之间的点(a组下面的一个箱形图,b组上面的一个箱形图)。在它们旁边,还有另外两个箱形图用于表示第26点和第50点之间的点,等等。如果它们不是处于理想的网格中(我认为获取网格既困难又丑陋),那就更好了:我更愿意它们“遵循”其对应的平滑线!
所有这些都无需使用构面(因为我必须将它们插入已经构面的绘图中:-))
我试图
bar <- foo %>%
group_by(group) %>%
mutate(cut = 12.5 * (time %/% 25)) %>%
ungroup()
bar %>%
ggplot(aes(x = time, y = value, color = group)) +
geom_point() +
geom_smooth(se = FALSE) +
geom_boxplot(aes(x = cut))
但它不起作用。
我尝试使用geom_boxplot()
而不是group
来致电x
bar %>%
ggplot(aes(x = time, y = value, color = group)) +
geom_point() +
geom_smooth(se = FALSE) +
geom_boxplot(aes(group = cut))
但是它绘制框线图时没有考虑分组甚至失去颜色(并且添加包含color = group
的冗余调用无济于事)
最后,我决定尝试一下:
bar %>%
ggplot(aes(x = time, y = value, color = group)) +
geom_point() +
geom_smooth(se = FALSE) +
geom_boxplot(data = filter(bar, group == "a"), aes(group = cut)) +
geom_boxplot(data = filter(bar, group == "b"), aes(group = cut))
有人知道是否可以通过一次调用geom_boxplot()
来获得它?
谢谢!
答案 0 :(得分:1)
这很有趣!我以前从未尝试将geom_boxplot
与连续的x
一起使用,也不知道它的行为。我认为正在发生的事情是,设置group
会覆盖colour
中的geom_boxplot
,因此它既不尊重继承的colour
美学,也不尊重重复的group
美学。我认为这种解决方法可以解决问题。我们将cut
和group_cut
变量组合到aes(group = group_cut)
中,该变量采用8个不同的值(每个所需的箱形图一个)。现在我们可以映射colour
并获得所需的输出。我认为这不是特别直观,因此可能值得在Github上进行改进,因为通常我们希望美学能够很好地结合在一起(例如,将linetype
和library(tidyverse)
bar <- tibble(
time = 1:100,
group = sample(c("a", "b"), 100, replace = TRUE) %>% as.factor()
) %>%
group_by(group) %>%
mutate(
value = rnorm(n()) + 10 * as.integer(group),
cut = 12.5 * ((time - 1) %/% 25), # modified this to prevent an extra boxplot
group_cut = str_c(group, cut)
) %>%
ungroup()
bar %>%
ggplot(aes(x = time, y = value, colour = group)) +
geom_point() +
geom_smooth(se = FALSE) +
geom_boxplot(aes(group = group_cut), position = "identity")
#> `geom_smooth()` using method = 'loess' and formula 'y ~ x'
结合起来效果很好)。
{"code":"DeploymentOutputEvaluationFailed","message":"Unable to evaluate template outputs: 'DatabaseConnectionString'. Please see error details and deployment operations. Please see https://aka.ms/arm-debug for usage details.","details":[{"code":"DeploymentOutputEvaluationFailed","target":"DatabaseConnectionString","message":"The template output 'DatabaseConnectionString' is not valid: The language expression property 'administratorLoginPassword' doesn't exist, available properties are 'administratorLogin, version, state, fullyQualifiedDomainName'.."}]}
由reprex package(v0.3.0)于2019-08-13创建