Michael Anderson
Michael Anderson

Reputation: 31

Consistent alpha scale across different ggplot2 maps

I am attempting to make a GIF of several different maps, showing how crime moves across the city at different times in the day. In order to do this, I am making several different stat_density2d() plots, one plot for each time interval. Here's the code:

data <- read.csv(".../CrimeLocationAndTime.csv", 
                 stringsAsFactors = FALSE)

# Get base map layer
denver = c(lon = -104.9903, lat =  39.7392)
denver_map = get_map(location = denver, zoom = 13, color = "bw")

# Get data slices
twoAMTimeSlice <- data[data$time == "2:00 AM",]
tenAMTimeSlice <- data[data$time == "10:00 AM",]

# Create density map
ggmap(denver_map, extent = "panel", maprange=FALSE) +
  stat_density2d(data = twoAMTimeSlice, 
                 aes(x = longitude, y = latitude,  fill = ..level.., alpha = ..level..),
                 size = 0.1, bins = 16, geom = 'polygon') +
  scale_fill_gradient(low = "green", high = "red", limits=c(0,2000)) + # Color scale
  scale_alpha(range = c(0.1, 0.4), guide = "legend") + # Here is the alpha scale
  geom_text(label = twoAMTimeSlice$time[1], x = -104.95, y=39.775) +
  theme(plot.title = element_text(size = rel(1.5), vjust = 1),
        axis.title = element_blank(),
        text = element_text(size = 12)) +
  labs(title = "Criminal Occurrences by Time of Day")

So here's my problem: I need my alpha scale to be consistent across all of my maps. Currently, if I make the graphs across different times with different amounts of crime, the alpha scale does not stay consistent. This is apparent in these pictures:

enter image description here

Observe how the green color in this picture is very transparent and the red is more opaque. This is the correct scale that I would like to apply to all maps.

enter image description here

Here, observe how the green is very opaque. You can also see the legend change from the last picture. This is bad. I would like the green in this picture to be just as opaque as the last one.

I have achieved this consistency of scale for the colors, using the limits argument to scale_fill_gradient. However, this argument gives wonky results when applied to scale_alpha.

Upvotes: 3

Views: 462

Answers (1)

Roman
Roman

Reputation: 4989

The solution was changing the limits to

  limits=c(0, 2000) 

(answered by OP in comments)

Upvotes: 1

Related Questions