使用position_jitterdodge无需绘制美观图

时间:2018-11-01 12:53:25

标签: r ggplot2

我想产生一个类似于以下代码的图。但是,我想通过“复制”来躲避,但是并没有实际映射美学(因为我想将填充和颜色分配给其他美学)。

dataset <- data_frame(sample = rep(c("Sample1","Sample2","Sample3", "Sample4"), each = 25),
                      replicate = sample(x = c("A", "B"), size = 100, replace = TRUE),
                      value = rnorm(n = 100, mean = 0, sd = 10))

ggplot(data = dataset, aes(x = sample, y = value, fill = replicate)) +
  geom_point(position = position_jitterdodge(jitter.width = 0.15, dodge.width = 0.75),
             show.legend = F)

我曾希望使用group = replicate代替fill = replicate,但这是行不通的。我可以想象出一种解决方法,例如将alpha = replicate用作美学,并在出现重复的情况下设置scale_alpha_manual(values = c(1, 1)),但我发现此解决方案并不理想,而是希望保留所有美学(x和x除外)。 y可供进一步使用)

ggplot(data = dataset, aes(x = sample, y = value, alpha = replicate)) +
   geom_point(position = position_jitterdodge(jitter.width = 0.15, dodge.width = 0.75),
              show.legend = F) +
   scale_alpha_manual(values = c(1, 1))

我希望得到的情节是:expected result

我希望我的问题有意义,有任何暗示吗? 最好, 伊万

1 个答案:

答案 0 :(得分:2)

您可以unite进行示例并复制列,并将其用作x轴,从而为样本之间的间距注入“占位符”值。

library(tidyverse)

set.seed(20181101)
dataset <- data_frame(sample = rep(c("Sample1","Sample2","Sample3", "Sample4"), each = 25), 
                      replicate = sample(x = c("A", "B"), size = 100, replace = TRUE), 
                      value = rnorm(n = 100, mean = 0, sd = 10))


dataset %>% 
  bind_rows({
    #create a dummy placeholder to allow for spacing between samples
    data.frame(sample = unique(dataset$sample),
               replicate = rep("Placeholder", length(unique(dataset$sample))),
               stringsAsFactors = FALSE)
  }) %>% 
  #unite the sample & replicate columns, and use it as the new x-axis
  unite(sample_replicate, sample, replicate, remove = FALSE) %>% 
  ggplot(aes(x = sample_replicate, y = value, color = replicate)) +
  geom_jitter() + 
  #only have x-axis labels for each sample
  scale_x_discrete(breaks = paste0("Sample", 1:length(unique(dataset$sample)), "_B"),
                   labels = paste0("Sample ", 1:length(unique(dataset$sample)))) + 
  labs(x = "Sample") +
  #don't show the Placeholder value in the legend
  scale_color_discrete(breaks = c("A", "B"))

sample_replicate