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

问题描述 投票:0回答:5

我开始学习«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»参数。

是否有人知道如何简单地做到这一点,以及是否通常这样做。如果不是,为什么呢?还有哪些替代方案?

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

r for-loop ggplot2 scatter-plot
5个回答
0
投票

我同意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

0
投票

我认为您不希望在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 

0
投票

这是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

0
投票

您使这个复杂化了。试试filter


0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.