'Adding ggplot object ontop of another ggplot object
I have made a basketball court in ggplot using geom_segments:
court <- ggplot(data = data.frame(c(0, 0)), xlim=c(0,50), ylim=c(0,50)) +
#NBA Court Boundaries
geom_segment(aes(x = 0, y = 0, xend = 0, yend = 47)) + #Left
geom_segment(aes(x = 50, y =47, xend = 50, yend = 0)) + #Right
geom_segment(aes(x = 0, y = 47, xend = 50, yend = 47)) + #Top/Half-court line
geom_segment(aes(x = 0, y = 0, xend = 50, yend = 0), color = 'black') + #Bottom
#Free-throw
#Line
geom_segment(aes(x = 19, y = 19, xend = 31, yend = 19)) +
#Top circle
geom_curve(aes(x = 19, y = 19, xend = 31, yend = 19), curvature = -1,
lineend = 'round', color = 'black') +
#Bottom circle
geom_curve(aes(x = 19, y = 19, xend = 31, yend = 19), curvature = 1,
linetype = 2, lineend = 'round') +
#Key
geom_segment(aes(x = 17, y = 19, xend = 33, yend = 19)) + #Top
geom_segment(aes(x = 17, y = 0, xend = 17, yend = 19)) + #Left
geom_segment(aes(x = 33, y = 0, xend = 33, yend = 19)) + #Right
#3-point Line
geom_segment(aes(x = 3, y = 0, xend = 3, yend = 14)) + #Left
geom_segment(aes(x = 47, y = 0, xend = 47, yend = 14)) + #Right
geom_curve(aes(x = 3, y = 14, xend = 47, yend = 14), curvature = -.75,
angle = 90) + #Curve
#Backboard
geom_segment(aes(x = 22, y = 4, xend = 28, yend = 4)) +
#Themes
coord_fixed() +
This code gives me an output of a court that looks like so:

I've managed to add this to my basketball shot data, but, am having trouble with the layering. If I add the court before my ggplot heatmap data, the heatmap will cover the court unless I use alpha, but that then makes the court quite hard to see:
heatmapAdjusted3 <- court +
stat_density2d(subset(nbaJumpAnd3ptNoise, shotType == '3pt'),
mapping = aes(x = x, y = y, fill = stat(density / max(density))),
geom = 'raster',
interpolate = TRUE,
n = 200,
#alpha = 0.9,
contour = FALSE) +
scale_fill_viridis_c(option = 'inferno', alpha = 0.9) +
xlab('x (ft)') +
ylab('y (ft)') +
scale_x_continuous(n.breaks = 3.5) +
theme(legend.position = 'none') +
theme(panel.background = element_rect(fill = 'white', colour = 'black')) +
coord_equal()
Which I think looks okay, but I would really like to find a way to layer the court on top of the given data instead to make the court lines a lot clearer. I have attempted making them white, but same issue as alpha just plays with the opacity. When trying to add the court object anywhere else in the code, it will seperate the two plots side by side.
Would love anyones input if they have any ideas at all. Thank you!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|

