0

I'm trying to make a time-lapse as I have graphs for different months and I would like them to be "animated". For instance, see below the maps for violent offences in Houston from the ggmap package sample.

January crimes

I want to make an animation, a little video going from month to month, so the colors of the graphs need to be consistent. For January the maximum is 900, whereas for February it is 1100 despite they would shoe the same tone of blue, which is wrong.

February crimes

I have tried to follow the steps shown here, using scale_alpha_continuous() and scale_color_discrete() but I haven't manage to fix it. Any idea on how to make the colors consistent setting a max for all the graphs? Any help hugely appreciated!

Code with data:

library(ggplot2)
library(ggmap)
library(mapproj)

crime <- data.frame(crime)
violent_crimes <- subset(crime, offense != "auto theft" & offense != "theft" & offense != "burglary")
violent_crimes$offense <- factor(violent_crimes$offense, levels = c("robbery", "aggravated assault", "rape", "murder"))
violent_crimes <- subset(violent_crimes,  + -95.39681 <= lon & lon <= -95.34188 & 29.73631 <= lat & lat <= 29.78400) # restrict to downtown

houston <- get_map("houston", zoom = 14)
HoustonMap <- ggmap(houston, extent = "device", legend = "topleft")

violent_crimes$month <- factor(violent_crimes$month)
months <- levels(violent_crimes$month)

for (i in levels(violent_crimes$month)){
        monthchosen <- months[i]
        violent_crimes_month <- subset(violent_crimes, month == as.character(monthchosen))

        HoustonMap +   
                stat_density2d( 
                        aes(x = lon, y = lat, fill = ..level..),
                        size = 2, bins = 4, data = violent_crimes_month,
                        geom = "polygon"
                )

        ggsave(file=paste0("Houston_",as.character(i),".png"), dpi=200)
}
Community
  • 1
  • 1
user3507584
  • 3,246
  • 5
  • 42
  • 66

1 Answers1

1

Just set the range of colors for each of the plot with an explicit scale setting

 + scale_fill_gradient(limits=c(0, 1500)))

If you add that to the plot, they should all go from 0 to 1500. You can change those values to whatever you want to make them consistent.

MrFlick
  • 195,160
  • 17
  • 277
  • 295