0

While creating a shot chart in R, I've been using some open source stuff from Todd W. Schneider's BallR court design (https://github.com/toddwschneider/ballr/blob/master/plot_court.R)

along with another Stack Overflow post on how to create percentages within hexbins (How to replicate a scatterplot with a hexbin plot in R?).

Both sources have been really helpful for me.

When I run the following lines of code, I get a solid hexbin plot of percent made for shots for the different locations on the court:

ggplot(shots_df, aes(x = location_y-25, y = location_x, z = made_flag)) +
  stat_summary_hex(fun = mean, alpha = 0.8, bins = 30) +
  scale_fill_gradientn(colors = my_colors(7), labels = percent_format(), 
                       name = "Percent Made")

However, when I include the BallR court design code snippet, which is shown below:

ggplot(shots_df, aes(x=location_y-25,y=location_x,z=made_flag)) +
   stat_summary_hex(fun = mean, alpha = 0.8, bins = 30) +
   scale_fill_gradientn(colors = my_colors(7), labels=percent_format(),  
                        name="Percent Made") +
   geom_path(data = court_points,
             aes(x = x, y = y, group = desc, linetype = dash),
             color = "#000004") +
   scale_linetype_manual(values = c("solid", "longdash"), guide = FALSE) +
   coord_fixed(ylim = c(0, 35), xlim = c(-25, 25)) +
   theme_court(base_size = 22)

I get the error: Error in eval(expr, envir, enclos) : object 'made_flag' not found, even though that the made_flag is 100% in the data frame, shots_df, and worked in the original iteration. I am lost on how to fix this problem.

1
  • 1
    Not knowing anything about your data or that theme, it's very difficult to know what's going on, but I notice that there is a second data frame (court_points) in the call to geom_path so I wonder if ggplot is trying to find made_flag there rather than in shots_df? Commented May 30, 2016 at 16:41

1 Answer 1

1

I believe your problem lies in the geom_path() layer. Try this tweek:

geom_path(data = court_points, aes(x = x, y = y, z = NULL, group = desc, linetype = dash))

Because you set the z aesthetic at the top, it is still inheriting in geom_path() even though you are on a different data source. You have to manually overwrite this with z = NULL.

Sign up to request clarification or add additional context in comments.

1 Comment

With that error in ggplot2, it's almost always about lingering inherited aesthetics. Cheers!

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.