0

I'm trying to plot multiple circles of different sizes on a plot using ggplot2's geom_point inside of a for loop. Every time I run it though, it plots all the circles, but all in the location of the last circle instead of in their respective locations as given by the data frame. Below is an example of the code I am running. I'm wondering how I would fix this or if there's a better way to get at what I'm trying to do here.

data <- data.frame("x" = c(0, 500, 1000, 1500, 2000),
 "y" = c(1500, 500, 2000, 0, 1000), 
 "size" = c(3, 5, 1.5, 4.2, 2.6)
)

g <- ggplot(data = data, aes(x = x, y = y)) + xlim(0,2000) + ylim(0,2000)
for(i in 1:5) {
  g <- g + geom_point(aes(x=data$x[i],y=data$y[i]), size = data$size[i], pch = 1)
}
print(g)

1 Answer 1

3

It's pretty rare to need a for-loop for a plot -- ggplot2 will take the whole dataframe and process it all without you needing to manage each row.

ggplot(data = data, aes(x = x, y = y, size = size)) + 
  geom_point(pch = 1)
Sign up to request clarification or add additional context in comments.

3 Comments

Nice ! I did not know that you could pass the size argument in the aes of ggplot ;)
If you take a look at ?geom_point to get its help page, you'll see a section on aesthetics. You can give it size, shape, and a host of other directions - and any of those can be dynamic based on your data.
I knew about the definition of group and color in the aes. Thanks for the tip ;) I just realized that my answer is completely wrong (not the right size vector). I deleted it. Yours is much better.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.