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

时间:2023-02-11 22:49:16

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.

我试图延时,因为我有不同月份的图表,我希望它们“动画”。例如,请参阅下面ggmap包示例中休斯顿暴力犯罪的地图。

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

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.

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

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

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!

我尝试使用scale_alpha_continuous()和scale_color_discrete()来执行此处显示的步骤,但我无法修复它。关于如何使颜色一致的所有想法设置所有图形的最大值?任何帮助非常感谢!

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

1 个解决方案

#1


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.

如果将其添加到绘图中,它们应该都从0到1500.您可以将这些值更改为您想要使它们保持一致的任何值。

#1


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.

如果将其添加到绘图中,它们应该都从0到1500.您可以将这些值更改为您想要使它们保持一致的任何值。