首页 > 解决方案 > 箱线图和散点图并排

问题描述

这对我来说似乎有些微不足道,但我的印象是我的解决方案有点......不必要的复杂。我想并排绘制箱线图和散点图。
例如:

x <- rep(letters[1:2],5)
y <- 1:5
my_data <- data.frame(x, y, stringsAsFactors = FALSE)

require(ggplot2)
require(dplyr)

my_data_mod <- my_data %>% mutate(x_mod = if_else(x == 'a', 1.2, 2.2))
# I want to plot the points shifted by a certain value - 
# as x is 1,2 for the box plot (see below), 
# I assigned 1.2 and 2.2 for the scatter plots

p <- ggplot(data = my_data) + 
  geom_boxplot(aes(x, y), width = .1) + 
  geom_jitter(data = my_data_mod, aes(x_mod, y), width = .1)

p

在此处输入图像描述

现在,当我查看箱线图的基础数据框时

str(ggplot_build(p)$data[[1]]$x)
num [1:2] 1 2

它显然为 x 分配了数字。那么有没有一种更简单的方法可以将“移动位置”分配给我的散点图?我试过了

geom_jitter(aes(as.numeric(x) + 0.2, y)

但这会引发警告

Warning messages:
1: In FUN(X[[i]], ...) : NAs introduced by coercion
2: In min(x) : no non-missing arguments to min; returning Inf
3: In max(x) : no non-missing arguments to max; returning -Inf
4: Removed 10 rows containing missing values (geom_point).

为什么???
一如既往,感谢您的帮助和指导。

标签: rggplot2

解决方案


这应该有效:

x <- rep(letters[1:2],5)
y <- 1:5
my_data <- data.frame(x, y, stringsAsFactors = FALSE)

require(ggplot2)
require(dplyr)

ggplot(data = my_data) + 
  geom_boxplot(aes(x, y), width = .1) + 
  geom_jitter(aes(as.numeric(as.factor(x)) + 0.2, y), width = .1)

在此处输入图像描述


推荐阅读