简体   繁体   English

当 ggplot 中的 col 不是 ID 时,如何为 ID 连接 geom_points?

[英]How do I connect geom_points for ID when col is not ID in ggplot?

I'm trying to make a ggplot (in Shiny): I have concentration-time data that I want to visualize.我正在尝试制作一个 ggplot(在 Shiny 中):我有我想要可视化的集中时间数据。 There's an option for the user to colour different groups in the plot, for example, Species, Antibodies, etc. However, I also want them to see the different concentration-time graphs for every ID, so what I actually want to achieve is that the data is colored by Species but the data points for each individual are connected.用户可以选择在 plot 中为不同的组着色,例如,物种、抗体等。但是,我也希望他们看到每个 ID 的不同浓度-时间图,所以我真正想要实现的是数据按物种着色,但每个个体的数据点都是相连的。

I can give you an example data set:我可以给你一个示例数据集:

dfc <- data.frame(
  ID = c(1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4),
  Conc = c(4, 3.5, 3, 1, 5, 4.5, 4, 2, 3, 2.5, 2, 1, 6, 5.5, 5, 4),
  Time = c(0.15, 1, 2, 3, 0.15, 1, 2, 3, 0.15, 1, 2, 3, 0.15, 1, 2, 3),
  Species= c("Monkey", "Monkey", "Monkey", "Monkey", "Monkey", "Monkey", "Monkey", "Monkey", "Mouse", "Mouse","Mouse","Mouse","Mouse","Mouse","Mouse","Mouse"))

I'm working on a Shiny app that is very big right now, so I won't bother you with all code, but that's just something easy right now.我正在开发一个 Shiny 应用程序,它现在非常大,所以我不会用所有代码来打扰你,但现在这很容易。 What I tried is this:我试过的是:

plot <- ggplot() + geom_point(dfc, mapping=aes(Time, Conc, col = Species)) + geom_line(dfc, mapping=aes("ID"))
plot

Obviously, this doesn't work and I'm also not sure how to do this.显然,这是行不通的,我也不确定该怎么做。 I hope someone can help me with this because I feel like the answer is simple, but I can't figure it out right now.我希望有人能帮我解决这个问题,因为我觉得答案很简单,但我现在想不通。

You could connect your points using group in your geom_line by ID like this:您可以使用geom_line中的group按 ID 连接您的点,如下所示:

library(ggplot2)
plot <- ggplot() + 
  geom_line(dfc, mapping=aes(x = Time, y = Conc, group = ID)) +
  geom_point(dfc, mapping=aes(Time, Conc, col = Species)) 
plot

Created on 2023-02-01 with reprex v2.0.2创建于 2023-02-01,使用reprex v2.0.2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM