如何使用 « for » 循环使用 ggplot2 绘制点?

How to plot points with ggplot2 using a « for » loop?

我开始学习 « ggplot2 » 和循环。所以现在,我尝试使用 « for » 循环使用 « ggplot2 » 绘制一些点。但是,我真的不知道该怎么做,也不知道这是否是个好主意。我检查了类似的问题,但我只是不明白。也许,我需要更多的解释。

我研究堆栈溢出有一段时间了,它对我帮助很大。但是,这是我的第一个问题,如果它遗漏了一些信息或者脚本没有正确公开,请告诉我哪里出了问题,我会在下次处理。

这是我的脚本 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.
      }

我也尝试使用 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])
        }
      }

点就是没有出现。我还尝试将值存储在向量中并将它们分配给 « x » 和 « y » 参数。

有人知道如何简单地做到这一点吗?如果这样做很常见。 如果不是,为什么? 还有什么选择?

谢谢你,祝你有美好的一天!

我同意 Rui Barradas 的观点,我会这样做:

CO2 %>%
  filter(Type == "Quebec" & Treatment == "nonchilled") %>% # Get nonchilled Quebec data
  ggplot(aes(x = conc, y = uptake)) +                      # Plot concentration and uptake
    geom_point()                                           # Plot as points

我认为您不会希望在 ggplot 函数中使用 for 循环。我建议将您的数据框过滤到您之前想要的条件,然后绘制所有这些点。

您必须列出所有您想要的条件并过滤掉以制作仅包含您想要绘制的那些观察结果的数据框。见下文:

CO2_quebec <- CO2 %>% 
  filter(Type=="Quebec") %>% #Filters out Type only in 'Quebec' 
  filter(Treatment == "nonchilled") #Filters out Treatment only for 'nonchilled' 

ggplot(data = CO2_quebec, mapping = aes(x = conc, y = uptake)) +  
  geom_point() #Note, your geom_point takes your x and y based on your ggplot line above unless otherwise specified 

这是ggplot的一个很常见的用法。

您可能正在寻找以下内容:

gg<- ggplot(data = CO2[CO2$Type=="Quebec" & CO2$Treatment=="nonchilled",], mapping = aes(x = conc, y = uptake))  + 
  geom_point()
gg

首先,你应该在做图之前过滤你的数据。它会让你的生活更轻松(就像我一样)。 然后,ggplot 是一个聪明的包:你不需要精确地绘制你想要绘制的每个点。如果你什么都不告诉他,它就会明白你想把所有东西都画出来(这就是为什么之前过滤有用的原因)。

此外,您可能会喜欢以下内容:

gg<- ggplot(data = CO2[CO2$Treatment=="nonchilled",], mapping = aes(x = conc, y = uptake, group=Type,color=Type))  + 
  geom_point()
gg

你太复杂了。试试 filter:

  library(tidyverse)
  data("CO2")

  CO2 %>% filter(Type == 'Quebec' & Treatment == 'nonchilled') %>% 
  ggplot(aes(x = conc, y = uptake)) + 
    geom_point()  

我相信其他答案很好地解决了上述问题,但如果您打算使用不同级别的类型和处理制作多个图表,您可以尝试使用 facet_grid:

CO2 %>%
  ggplot(mapping = aes(x = conc, y = uptake)) +
  geom_point() +
  facet_grid(. ~ Type + Treatment)