0

I am having some trouble trying to plot a density map for crime in my city. I'm using the two-dimensional kernel density estimation through the stat_density2d() function. No matter what I change and/or rearrange, I am continually receiving the error message

Discrete value supplied to continuous scale

I ran the str function to check the structure; Lon(gitude) was being read as a character.

OakTownMap +
  stat_density2d(aes(x = lon, y = lat, fill = ..level.. ,alpha=..level..), bins = 10, geom ="polygon", data = Non_Violent_Crime) +
  scale_fill_gradient(low = "black", high = "red")+
  ggtitle("Map of Non-Violent Crime Density in Oakland ")

I'm truly lost and a little frustrated because I'm sure this requires a very simple adjustment to placement of lon and lat arguments or change in function(?). Should I just change lon from char to num?

str return image

Rui Barradas
  • 70,273
  • 8
  • 34
  • 66

1 Answers1

0

From the screenshot it looks like you need to coerce lon into a numeric vector. try Non_Violent_Crimes$lon <- as.numeric(Non_Violent_Crimes$lon) before you add it to ggplot. alternatively, when you add the geometry, change "x=lon" into "x=as.numeric(lon)". This directly addresses the error you are receiving.

Brian Fisher
  • 1,305
  • 7
  • 17
  • Thank you! While this does address the error, however, no geometry were plotted over the map. The code runs, but nothing gets plotted. Should I make changes to the structure of the entire dataset? – scarceabundance Sep 26 '19 at 20:23
  • @scarceabundance We probably need to see a bit more of the objects involved. I'm assuming that OakTownMap is a ggplot object that is in the same coordinate system you are trying to plot to. Can you provide more information. You might try adding the density plot to a blank map. Further, check your longitude values and make sure they have a reasonable level of precision - the screen shot only shows degrees, which would place your points 20km east of Oakland. – Brian Fisher Sep 26 '19 at 20:56
  • Working on that now. Thanks again! – scarceabundance Sep 26 '19 at 21:12
  • The dataset had mislabeled the longitude and latitude columns, so they were the opposite of precise. The code is fully functional. Thanks again, Brian – scarceabundance Sep 27 '19 at 02:59