简体   繁体   中英

How to plot a Circle Using geom_circle function

My goal is to draw the dimensions/lines of an NBA basketball court using a combination of the ggplot2 and ggforce packages. I have used the + geom_segment() layer to successfully draw the line segments (sidelines, free throw lines, etc.), but I am having a hard time using the + geom_circle() and + geom_arc() functions to draw the circles and circle arcs (three point line, half-court circle, etc.)

My code is as follows, where object 'sample' is simply a data frame of shots, with x and y coordinates:

ggplot(sample, aes(shot_x, shot_y)) +
geom_point(color = "red", alpha = .2) +
geom_segment(aes(x = 0, xend = 94, y = 0, yend = 0)) +
geom_segment(aes(x = 0, xend = 94, y = 50, yend = 50)) +
geom_segment(aes(x = 0, xend = 0, y = 0, yend = 50)) +
geom_segment(aes(x = 94, xend = 94, y = 50, yend = 0)) +
geom_segment(aes(x = 0, xend = 14, y = 3, yend = 3)) +
geom_segment(aes(x = 80, xend = 94, y = 3, yend = 3)) +
geom_segment(aes(x = 0, xend = 14, y = 47, yend = 47)) +
geom_segment(aes(x = 80, xend = 94, y = 47, yend = 47)) +
geom_segment(aes(x = 47, xend = 47, y = 0, yend = 50)) +
geom_segment(aes(x = 0, xend = 19, y = 19, yend = 19)) +
geom_segment(aes(x = 0, xend = 19, y = 31, yend = 31)) +
geom_segment(aes(x = 75, xend = 94, y = 19, yend = 19)) +
geom_segment(aes(x = 75, xend = 94, y = 31, yend = 31)) +
geom_segment(aes(x = 19, xend = 19, y = 19, yend = 31)) +
geom_segment(aes(x = 75, xend = 75, y = 19, yend = 31)) +
geom_segment(aes(x = 4, xend = 4, y = 22, yend = 28)) +
geom_segment(aes(x = 90, xend = 90, y = 22, yend = 28)) +
coord_fixed(ratio = 1)

When I add:

+ geom_circle(aes(x0 = 47, y0 = 25, r = 6))

(which should draw a circle at half-court), no circles appear on the visualization, and the result includes the initial graph (line segment and points for shots), along with a duplicate of all the data points, but offset up and to the right. To be clear, no errors occur, it's just that the result is not what I'm going for.

Also, when I remove the geom_point() layer entirely, and start the code like:

ggplot() +
geom_segment(...)

Then I can add the geom_circle() layer successfully. However, I need to be able to add the circle and also include the data points.

Any idea why this is happening, or what I'm doing wrong? Thanks!

Not sure why, but adding inherit.aes = FALSE inside the geom_circle call fixes it.

# generate sample data
sample = data.frame(shot_x = c(10, 20), shot_y = c(30, 40))
ggplot(sample, aes(shot_x, shot_y)) +
  # ... all your segment lines
  coord_fixed(ratio = 1) +
  geom_circle(aes(x0 = 47, y0 = 25, r = 6), inherit.aes = FALSE)

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM