I started to learn « ggplot2 » and loops since some times. So now, I try to plot some points with « ggplot2 » using a « for » loop. But, I don't really know how to do it, and I don't really know if it's a good idea. I checked over the similar questions and I just don't understand. Maybe, I need more explications.
I've been surfing on stack overflow for a while and it helped me a lot. However, it's my first question here and if it miss some informations or if the script is not correctly exposed, just tell me what's wrong and I'll take care it for the next time.
Here's my script with geom_point() :
library(tidyverse)
data("CO2")
ggplot(data = CO2, mapping = aes(x = conc, y = uptake)) + # I think that I must do this.
for (i in 1:nrow(CO2)) { # For each line of the dataset.
if(CO2$Type[i] == "Quebec" & CO2$Treatment[i] == "nonchilled") { # Test these conditions.
geom_point(mapping = aes(x = CO2$conc[i], y = CO2$uptake[i])) # If they are true, add the point using geom_point.
} # And eventually, I would like to add more « for » loops.
}
And I also try with annotate() :
ggplot(data = CO2, mapping = aes(x = conc, y = uptake)) +
for (i in 1:nrow(CO2)) {
if(CO2$Type[i] == "Quebec" & CO2$Treatment[i] == "nonchilled") {
annotate(geom = "point", x = CO2$conc[i], y = CO2$uptake[i])
}
}
The points just don't appear. I also try to stock the values in vectors and assigned them to the « x » et « y » arguments.
Is someone knows how to do that simply, and if it's common to do that. If it's not, why? And what are the alternatives?
Thank you and have a good day!
data = subset(CO2, Type == "Quebec" & Treatment == "nonchilled"). In ggplot, you never need that type of code.tidyversethat also loads packagedplyr,CO2 %>% filter(Type == "Quebec", Treatment = "nonchilled") %>% ggplot(mapping = ...). Note that the pipe means you don't pass adataargument toggplot.gganimatepackage for that.ggplotgrob iteratively in aforloop (ultimately not what you need here): I'd start withgg <- ggplot(data, aes(...)), thenfor (i in ...) { gg <- gg + geom_*(...); }, then ultimately deal with theggpost-loop. But please, don't try to use this in this example, as you are defeating so many efficiencies inggplot2and in R by trying to do it in a loop.