Adding circle to graph?

3,152 views
Skip to first unread message

Garrett Grolemund

unread,
Mar 15, 2010, 2:15:48 PM3/15/10
to ggp...@googlegroups.com
Hello guys,

Is there a way to add circles to graphs similar to how geom_rect() adds rectangles? Specifically, I'm trying to add a ring around the origin that would encapsulate all points within a certain distance of (0, 0).

I've attempted to do this using geom_point(), but I'm not sure how to map the radius of the ring/point to my variable of interest. I want to avoid manually setting the size parameter each time I make this type of graph. Plus, I'm not sure which value of size will give me a point with the desired radius.

# My desired radius variable
threshold <- 20

ggplot(cars, aes((speed - 15) * 6, dist - 60)) +
  geom_point() +
  coord_equal() +
  geom_point(aes(x = 0, y = 0), colour = "red", shape = 1, size = threshold)

Here's a version of the attempt using geom_rect(). The rectangle has the correct width and height, but of course its not a circle.

threshold <- 20

ggplot(cars, aes((speed - 15) * 6, dist - 60)) +
  geom_point() +
  coord_equal() +
  geom_rect(aes(xmin = -threshold, xmax = threshold, ymin = -threshold, ymax = threshold), colour = "red", fill = NA)

Thanks,
Garrett

baptiste auguie

unread,
Mar 15, 2010, 3:57:59 PM3/15/10
to ggp...@googlegroups.com
Hi,

My first naive attempt was to use scale_size_identity() which clearly
won't work since the unit of the point symbols is hard-coded to "mm"
in geom_point(). Inspired by this example, one could argue that
scale_size_identity() should perhaps switch to "native" units instead?
colour_identity, shape_identity are other examples where the actual
physical output is directly controlled; I think for size, native units
could be more intuitive/useful than "mm". What do you think?


Best,

baptiste

> --
> You received this message because you are subscribed to the ggplot2 mailing
> list.
> To post to this group, send email to ggp...@googlegroups.com
> To unsubscribe from this group, send email to
> ggplot2+u...@googlegroups.com
> For more options, visit this group at
> http://groups.google.com/group/ggplot2

hadley wickham

unread,
Mar 15, 2010, 4:03:18 PM3/15/10
to baptiste auguie, Garrett Grolemund, ggp...@googlegroups.com
The problem is that geom_point but depending on the x and y scales,
you may actually need a oval.

The easiest way to draw a circle is to generate the coordinates
yourself and then use geom_polygon:

angle <- seq(-pi, pi, length = 50)
df <- data.frame(x = sin(angle), y = cos(angle))

qplot(x, y, data = df, geom = "polygon")

or

+ geom_polygon(aes(x, y), data = df, inherit.aes = F)

Hadley

--
Assistant Professor / Dobelman Family Junior Chair
Department of Statistics / Rice University
http://had.co.nz/

Reply all
Reply to author
Forward
0 new messages