R语言 使用ggplot2绘制数据框中的选定样本时出现问题

kr98yfug  于 2023-03-27  发布在  其他
关注(0)|答案(1)|浏览(131)

我试图从R中的 Dataframe 中的较大样本组中选择样本进行绘图。
Dataframe 构造如下:

round1Counts <- data.frame(
  Sample = c(round1[1:20,1], "LowerLimit", "UpperLimit"),
  Day = c(rep("1",22), rep("3",22), rep("6",22), rep("8",22)),
  Counts = c(strtoi(round1[1:20,2]), 50000, 240000, strtoi(round1[1:20,3]), 50000, 240000, strtoi(round1[1:20,4]), 50000, 240000, strtoi(round1[1:20,5]), 50000, 240000)
)
round1Counts$Sample <- as.character(round1Counts$Sample)
round1Counts$Sample <- factor(round1Counts$Sample, levels=c(round1[,1],"LowerLimit","UpperLimit"))

Round1是一个20 × 5的矩阵,其中第一列是ID列表,后面的4个是不同的时间点。
我的策略到目前为止在包括所有样本但仅选择某些时间点时有效,

# All samples, days 1 & 3
ggplot(data = round1Counts[1:44,], aes(x = Day[1:44], y = Counts[1:44], group = Sample[1:44], color = Sample[1:44])) +
  geom_line() +
  theme(panel.background = element_rect(fill = "white", colour = "grey50"))

但当我试图分离某些样本时却失败了

# First 5 samples, days 1 & 3
ggplot(data = round1Counts[c(1:5,23:27),], aes(x = Day[c(1:5,23:27)], y = Counts[c(1:5,23:27)], group = Sample[c(1:5,23:27)], color = Sample[c(1:5,23:27)])) +
  geom_line() +
  theme(panel.background = element_rect(fill = "white", colour = "grey50"))

生成以下错误:

geom_path: Each group consists of only one observation. Do you need to adjust the group aesthetic?
Warning message:
Removed 5 row(s) containing missing values (geom_path).

该函数似乎没有识别出round1Counts[1,]和round1Counts[23,]引用的是同一个样本,但我希望通过样本分组来允许识别,因为相同的值位于这两个索引处。

ycl3bljg

ycl3bljg1#

您已经使用data=round1Counts[c(1:5, 23:27),]对行进行了采样。aes()中的术语应该只是 * 列名 *,而不是对实际数据向量的引用。您在data=...中指定的内容已经足以让ggplot知道您想要包括第1到5行以及第23到27行。
因此,应该改为这样做(为清晰起见重新格式化):

ggplot(
  data = round1Counts[c(1:5,23:27),],  # already samples your rows for you
  aes(
    x = Day,
    y = Counts,
    group = Sample,
    color = Sample  # kind of redundant here
  )
) +
  geom_line() +
  theme(
    panel.background = element_rect(fill = "white", colour = "grey50")
  )

相关问题