0

I am trying to display a series of plots in R based on a condition with a variable taking a sequence of values something like simple clustering. I have data frame with numerical columns X and Y respectively. There is also a Z column with text values (categorical variable). I am trying the following code but it doesn't work. The code works fine if instead I use numerical values for i and j, example i=50 and j=100.

my data frame: new.data, columns: X, Y, Z

 j=0
 for(i in seq(0, 500, by = 50)){
   j=i+50
   PlotData <- new.data[(new.data$X <j) & (new.data$X >i),]
   ggplot (PlotData, aes(X, Y, color = Z)) + geom_point()
 }
Richard Telford
  • 9,558
  • 6
  • 38
  • 51
tkyo
  • 75
  • 1
  • 12

1 Answers1

1

You want to explicitly print the plot in the loop. Replacing the ggplot() line with this should work:

p <- ggplot (PlotData, aes(X, Y, color = Z)) + geom_point()
print(p)

Setting i, j individually rather than in a loop works because the print statement is run implicitly outside the brackets. See this post for details: ggplot plots in scripts do not display in Rstudio

Community
  • 1
  • 1
uut
  • 1,834
  • 14
  • 17