使用stat_density2d函数对几个ggplot2图表进行一致着色

时间:2015-07-08 15:29:17

标签: r dictionary ggplot2 ggmap

我试图延时,因为我有不同月份的图表,我希望他们能够#34;动画"。例如,请参阅下面ggmap套餐样本中休斯顿暴力犯罪的地图。

January crimes

我想制作一个动画,一个月的视频,所以图表的颜色需要保持一致。 1月份最高为900,而2月为1100,尽管他们会采用相同的蓝色调,这是错误的。

February crimes

我尝试使用scale_alpha_continuous()scale_color_discrete()按照more on parsing dates from timestring显示的步骤操作,但我无法解决问题。关于如何使颜色保持一致的任何想法都为所有图形设置了最大值?任何帮助非常感谢!

包含数据的代码:

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)
}

1 个答案:

答案 0 :(得分: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.