Search code examples
rggplot2bubble-charthclust

Prevent Background Image from Covering Plot


I am generating bubble charts from NBA shot data clusters. The final form of the data is:

data

Where Group.1 is the index of the cluster, ad.SHOT_MADE_FLAG is the field goal percent for the cluster, coords.x1 and x2 are the mean x and y coordinates of the points in that cluster, and x is the number of shots (x and y points) in that cluster.

I am plotting the data with the following:

courtImg.URL <- "https://thedatagame.files.wordpress.com/2016/03/nba_court.jpg"
court <- rasterGrob(readJPEG(getURLContent(courtImg.URL)),
                width=unit(1,"npc"), height=unit(1,"npc"))

p6 <- ggplot(final, aes(x = final$coords.x1, y = final$coords.x2, size = 
  final$x,fill=final$ad.SHOT_MADE_FLAG)) +
  geom_point(shape = 21) +
  annotation_custom(court, -250, 250, -52, 418) + 
  scale_x_continuous() +
  coord_fixed() + 
  scale_fill_gradientn(colours = c("Blue","Red")) +
  theme(line = element_blank(),
        axis.title.x = element_blank(),
        axis.title.y = element_blank(),
        legend.title = element_blank(),
        plot.title = element_text(size = 17, lineheight = 1.2, face = "bold")) +
  ggtitle("Stephen Curry Shot Chart")

p6

This outputs the following chart

plot

I am wanting to solve two issues with this. First the background image is covering up the majority of the data. Second, I want to only show the plot below the 418 point on the y axis. I dont want to show shots from the backcourt as they aren't as relevant. Just for reference, when I remove the annotation_custom() line, it shows the following plot:

plot

So the implementation of the annotation_custom line appears to be part of the problem. Any help would be greatly appreciated. Thanks!


Solution

  • ggplot2 draws plot layers in the order you specify them. To move the image of the court below the points, put it first in the drawing order. The other fix that might make your plot a little nicer is to make the panel background transparent so that you can see the points on top of the image, which I assume is what you're going for.

    You can set the ends of the plots using the limits argument in scale_y_continuous().

    Updated plotting code:

    p6 <- ggplot(final, aes(x = final$coords.x1, y = final$coords.x2, size = 
      final$x,fill=final$ad.SHOT_MADE_FLAG)) +
      annotation_custom(court, -250, 250, -52, 418) + 
      geom_point(shape = 21) +
      scale_x_continuous() +
      scale_y_continuous(limits=c(-52,418)) +
      coord_fixed() + 
      scale_fill_gradientn(colours = c("Blue","Red")) +
      theme(line = element_blank(),
        axis.title.x = element_blank(),
        axis.title.y = element_blank(),
        legend.title = element_blank(),
        panel.background = element_rect(fill="transparent"),
        plot.title = element_text(size = 17, lineheight = 1.2, face = "bold")) +
      ggtitle("Stephen Curry Shot Chart")
    
    p6