将数据框拆分为两组

时间:2015-07-11 07:51:58

标签: r ggplot2 dataframe visualization

我已经模拟了这个data.frame

library(plyr); library(ggplot2)
count <- rev(seq(0, 500, 20))
tide <- seq(0, 5, length.out = length(count))
df <- data.frame(count, tide)

count_sim <- unlist(llply(count, function(x) rnorm(20, x, 50)))
count_sim_df <- data.frame(tide=rep(tide,each=20), count_sim)

它可以像这样绘制:

ggplot(df, aes(tide, count)) + geom_jitter(data = count_sim_df, aes(tide, count_sim), position = position_jitter(width = 0.09)) + geom_line(color = "red")

enter image description here

我现在想将count_sim_df分成两组:highlow。当我绘制分割count_sim_df时,它应该看起来像这样(绿色和蓝色的一切都是照片)。我发现棘手的一点是在high的中间值lowtide之间重叠。

这就是我想将count_sim_df分为高和低的方式:

  • count_sim_df的一半分配给high,将count_sim_df的一半分配给low
  • 重新分配count的值,以便在high
  • 的中间值周围创建lowtide之间的重叠

enter image description here

2 个答案:

答案 0 :(得分:2)

这是我修改过的建议。我希望它有所帮助。

middle_tide <- mean(count_sim_df$tide)
hilo_margin <- 0.3
middle_df <- subset(count_sim_df,tide > (middle_tide * (1 - hilo_margin)))
middle_df <- subset(middle_df, tide < (middle_tide * (1 + hilo_margin)))
upper_df <- count_sim_df[count_sim_df$tide > (middle_tide * (1 + hilo_margin)),]
lower_df <- count_sim_df[count_sim_df$tide < (middle_tide * (1 - hilo_margin)),]
idx <- sample(2,nrow(middle_df), replace = T)
count_sim_high <- rbind(middle_df[idx==1,], upper_df)
count_sim_low <- rbind(middle_df[idx==2,], lower_df)
p <- ggplot(df, aes(tide, count)) + 
   geom_jitter(data = count_sim_high, aes(tide, count_sim), position = position_jitter(width = 0.09), alpha=0.4, col=3, size=3) + 
   geom_jitter(data = count_sim_low, aes(tide, count_sim), position = position_jitter(width = 0.09), alpha=0.4, col=4, size=3) + 
   geom_line(color = "red")

enter image description here

我可能仍然没有完全理解你的程序分为高和低,特别是你的意思是&#34;重新分配计数的价值&#34;。在这种情况下,我在tide的中间值周围定义了一个30%的重叠区域,并将该过渡区域内的一半点随机分配给&#34;高&#34;另一半是&#34;低&#34;组。

答案 1 :(得分:1)

这是一种使用相对较少的代码生成样本数据集和分组的方法,只需基础R:

library(ggplot2)
count <- rev(seq(0, 500, 20))
tide <- seq(0, 5, length.out = length(count))
df <- data.frame(count, tide)

count_sim_df <- data.frame(tide = rep(tide,each=20),
                           count = rnorm(20 * nrow(df), rep(count, each = 20), 50))
margin <- 0.3
count_sim_df$`tide level` <-
  with(count_sim_df,
    factor((tide >= quantile(tide, 0.5 + margin / 2) |
           (tide >= quantile(tide, 0.5 - margin / 2) & sample(0:1, length(tide), TRUE))),
           labels = c("Low", "High")))
ggplot(df, aes(x = tide, y = count)) +
  geom_line(colour = "red") +
  geom_point(aes(colour = `tide level`), count_sim_df, position = "jitter") +
  scale_colour_manual(values = c(High = "green", Low = "blue"))