Agrosel
Agrosel

Reputation: 539

Object not being found when using ggplot2 in R

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.

Upvotes: 0

Views: 1729

Answers (1)

Nate
Nate

Reputation: 10671

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.

Upvotes: 1

Related Questions