[英]Overlay geom_line within a categorical x axis for each group - ggplot2
方框代表连续变量在组内的分布; 红色圆圈是显示所有实际观察的点。 到目前为止,一切都很好。 使用geom_boxplot
+ geom_point
和群体美学,这很简单。
以下是两个转折点:
一些上下文:此 plot 显示产品的使用(Y 轴)与允许的使用(X)。 X 轴组是互斥的离散层,本质上是一个无限的连续使用变量。 EG, 1-4, 5-9, 10-20 等等。从视觉的角度来看,plot 在这些组中的连续对我来说并不疯狂,这有意义吗? 但我不知道如何开始让ggplot2
同意我的观点。
我的偏好是让箱形图沿 X 轴均匀分布,但如果我需要从轴连续开始,并让组在 X 轴上占据成比例的空间,那么我会满足于此(可能使用记录轴以防止较低、狭窄的组被完全弄脏。
这应该作为示例数据:
df <- structure(list(usage = c(1L, 4L, 2L, 5L, 4L, 1L, 2L, 98L, 9L,
4L, 6L, 6L, 1L, 2L, 2L, 2L, 3L, 2L, 5L, 1L), allowed = c(2, 20,
3, 3, 5, 5, 1, 1, 1, 5, 10, 5, 7, 12, 2, 5, 23, 10, 5, 2), id = c(1055L,
2155L, 6637L, 11068L, 2070L, 8524L, 9157L, 5963L, 7593L, 3470L,
3557L, 7469L, 9142L, 408L, 9446L, 1552L, 4788L, 7233L, 8464L,
2188L), group = c("A", "B", "A", "A", "A", "A", "A", "A", "A",
"A", "B", "A", "B", "B", "A", "A", "B", "B", "A", "A")), row.names = c(NA,
-20L), class = c("tbl_df", "tbl", "data.frame"))
这是我为你想出的:
# you had some values that were = 98 in usage and throwing everything off..
df <- df %>% dplyr::filter(usage < 50)
p <-
ggplot(df, aes(allowed, usage)) +
geom_boxplot(aes(group=group)) +
geom_point() +
geom_smooth(alpha=0, method='lm') +
facet_wrap(~group, scales='free_x', strip.position = 'bottom') +
theme_classic() +
theme(
axis.text.x = element_blank(), # remove x axis text
axis.ticks.x = element_blank(), # remove tick marks on x axis
axis.title.x = element_blank(), # remove title for axis
strip.background = element_blank(), # no box on facet label
strip.placement = 'outside', # facet label is outside axis line
strip.text = element_text(size=12),
panel.spacing.x = unit(0, 'pt') # remove space between facets
)
p
一般的想法是考虑你在这里有 2 x 轴。 您想要 plot 您的点的主轴是df$allowed
,而您想要基于df$group
进行分组。 我在这里能想到的最简单的解决方案是将df$group
的每个值视为一个单独的方面,然后通过将它们之间的空间设置为零来将这些方面“缝合”在一起。 似乎运作良好。
否则,这里唯一的评论是,这些框可能有点靠得太近,您不喜欢 - 区分一组的点以与另一组区分开来。 由于每个组都是一个方面,因此是一个完全独立的 plot,您可以通过添加/扩展每个方面的主要 x 轴来“挤压”这些框,如下所示:
p + scale_x_continuous(expand=expansion(mult=c(0.8)))
注意:我必须删除一些使用中的超高值才能真正正确地看到你的图。 我想这是复制数据的产物(如缺失值)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.