Take the 2-minute tour ×
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

everybody, sorry for disturb, but I am being quite new with r faced a crucial difficuty: I want to create an animated map of Russin with changes in unemployment with differnt years, like. On the image you can see data for one yearenter image description here

require(sp)
require(maptools)

require(RColorBrewer)
require(rgdal)
 rus<-url("http://www.filefactory.com/file/4h1hb5c1cw7r/n/RUS_adm1_RData")
print(load(rus))


unempl <- read.delim2(file="C:\\unempl1.txt", header = TRUE, 
        sep = ";",quote = "", dec=",", stringsAsFactors=F)

gadm_names <-gadm$NAME_1
total <- length(gadm_names)
pb <- txtProgressBar(min = 0, max = total, style = 3) 

order <- vector()
for (i in 1:total){  

  order[i] <- agrep(gadm_names[i], unempl$region, 
                     max.distance = 0.2)[1]
 setTxtProgressBar(pb, i)               # update progress bar
}


col_no <- as.factor(as.numeric(cut(unempl$data[order],
                    c(0,2.5,5,7.5,10,15,100))))


levels(col_no) <- c("<2,5%", "2,5-5%", "5-7,5%",
                    "7,5-10%", "10-15%", ">15%")


gadm$col_no <- col_no
myPalette<-brewer.pal(6,"Purples")



proj4.str <- CRS("+init=epsg:3413 +lon_0=105")
gadm.prj <- spTransform(gadm, proj4.str)

spplot(gadm.prj, "col_no", col=grey(.9), col.regions=myPalette,
main="Unemployment in Russia by region")

The result, which I willing to get is something like animation here: http://spatial.ly/2011/02/mapping-londons-population-change-2011-2030/ However, I googled a lot, read a number of themes in http://stackoverflow.com including the following: Creating a Movie from a Series of Plots in R, but couldn't do the right thing still.

thank you in advance!

I've comed up with something like this, can anyone please tell me where is the mistake:

require(animation)
    require(sp)
    require(RColorBrewer) 
    require(classInt)     
require(rgdal)
 rus<-url("http://www.filefactory.com/file/4h1hb5c1cw7r/n/RUS_adm1_RData")
print(load(rus))




unempl1 <- read.delim2(file="C:\\unempl11.txt", header = TRUE, 
        sep = ";",quote = "", dec=",", stringsAsFactors=F)
unempl2<- read.delim2(file="C:\\unempl12.txt", header = TRUE, 
        sep = ";",quote = "", dec=",", stringsAsFactors=F)

gadm_names <-gadm$NAME_1


total <- length(gadm_names)
pb <- txtProgressBar(min = 0, max = total, style = 3) 

order <- vector()

for (i in 1:total){  

  order[i] <- agrep(gadm_names[i], unempl1$region, 
                     max.distance = 0.2)[1]
 setTxtProgressBar(pb, i)               # update progress bar
}


for (l in 1:total){  

  order[l] <- agrep(gadm_names[l], unempl2$region, 
                     max.distance = 0.2)[1]
 setTxtProgressBar(pb, i)               # update progress bar
}

col_no_1 <- as.factor(as.numeric(cut(unempl1$data[order],
                    c(0,2.5,5,7.5,10,15,100))))

col_no_2<- as.factor(as.numeric(cut(unempl2$data[order],
                    c(0,2.5,5,7.5,10,15,100))))
saveHTML(
      for(k in 1:2) {
        try<-get(paste("col_no_", k, sep = ""))

levels(try) <- c("<2,5%", "2,5-5%", "5-7,5%",
                    "7,5-10%", "10-15%", ">15%")


gadm$col_no <- try

myPalette<-brewer.pal(6,"Purples")



proj4.str <- CRS("+init=epsg:3413 +lon_0=105")
gadm.prj <- spTransform(gadm, proj4.str)

spplot(gadm.prj, "col_no", col=grey(.9), col.regions=myPalette,
main="Unemployment in Russia by region")
},img.name = "map", htmlfile = "unrus2.html")

Here is data to be able to reproduce the code

share|improve this question
    
Re The edit: what is going wrong with the code? –  whuber Jun 18 '13 at 22:11
    
Since your example is not reproducible it is difficult to troubleshoot. A few things jump out 1) you are applying a spatial transform in a loop, so you are doing it repeatedly 2) you are creating an object called "try" which is also an R function 3) you could iterate through actual column names ie., for(i in c("Var1","Var2")) the way you currently have it codded is very convoluted 4) your call to spplot is not correct, you are passing it a nonsense vector. –  Jeffrey Evans Jun 18 '13 at 23:01
    
I am really sorry for being such a not-understanding, but this is my first real experience with R ever, I've added the data in main question, if it won't bother you can you please suggests ways for improvement as I really ran ut of ideas –  Ruvin Rafailov Jun 19 '13 at 8:10
add comment

4 Answers 4

up vote 2 down vote accepted

This is as far as I go. You should be able to figure it out based on this code. Once again, since your problem is not reproducible I had to create dummy data to illustrate the solution. One odd aspect in using spplot is that since it uses lattice to create the plot you need to create an object and then print the object. Otherwise you do not get a plot.

require(animation)
require(sp)
require(RColorBrewer) 
require(classInt)     
require(rgdal)

load(url("http://www.filefactory.com/file/4h1hb5c1cw7r/n/RUS_adm1_RData"))
closeAllConnections()

# Set color palette
myPalette <- brewer.pal(6,"Purples")

# Reproject data
gadm <- spTransform(gadm, CRS("+init=epsg:3413 +lon_0=105"))

# Create dummy unployment data with 10% change in gadm object 
gadm@data$uemp2000 <- runif(dim(gadm)[1],0,50)
gadm@data$uemp2001 <- gadm@data$uemp2000 + (gadm@data$uemp2000 * 0.10) 
gadm@data$uemp2002 <- gadm@data$uemp2001 + (gadm@data$uemp2001 * 0.10) 
gadm@data$uemp2003 <- gadm@data$uemp2002 + (gadm@data$uemp2002 * 0.10) 
gadm@data$uemp2004 <- gadm@data$uemp2003 + (gadm@data$uemp2003 * 0.10) 
gadm@data$uemp2005 <- gadm@data$uemp2004 + (gadm@data$uemp2004 * 0.10) 

# Coerce into factors with defined levels
for( i in c("uemp2000","uemp2001","uemp2002","uemp2003","uemp2004","uemp2005") ) {
  gadm@data[,i] <- as.factor(as.numeric(cut(gadm@data[,i], 
                             c(0,2.5,5,7.5,10,15,100)))) 
    levels(gadm@data[,i]) <- c("<2,5%", "2,5-5%", "5-7,5%",
                               "7,5-10%", "10-15%", ">15%")                          
    } 

saveHTML(
  for(i in c("uemp2000","uemp2001","uemp2002","uemp2003","uemp2004","uemp2005")) {
    sp.plot <- spplot(gadm, i, col=grey(.9), col.regions=myPalette,
                      main=paste("Unemployment in Russia", i, sep=" - ") )
      print( sp.plot )
},img.name = "map", htmlfile = "unrus2.html")
share|improve this answer
    
Thank you! I'll try it immediately. Just one question gadm@data$uemp2001 <- gadm@data$uemp2000 + (gadm@data$uemp2000 * 0.10) can I here load txt data instead of given random, no troubleshooting will take place? –  Ruvin Rafailov Jun 20 '13 at 19:23
    
Yes, that code is just associated with creating example data. You would want to use your own data. –  Jeffrey Evans Jun 21 '13 at 3:50
add comment

Take a look at the animation package. One of the functions worth exploring, that does not require 3rd party software, is "saveHTML".

Using the "saveHTML" function in the animation package is very straight forward. Here is example code where I create an animation of a randomized population change. The "expr" argument defines the plotting function you want to pass to the animation. As you can see in the below code I used a for loop to plot each simulated column.

    require(animation)
    require(sp)
    require(RColorBrewer) 
    require(classInt)     

# Load your data and add random population change column
    load(url("http://www.gadm.org/data/rda/GBR_adm2.RData"))
      for( i in 1:10 ) {
        gadm@data[paste("Year",i, sep="")] <- runif(dim(gadm)[1],0,1) 
       }

# Create HTML animation using for loop for each simulated column    
    saveHTML(
      for(x in names(gadm@data)[19:28]) { 
      ani.options(interval = 0.5)  
       plotvar <- gadm@data[,x]
          nclr <- 9
         plotclr <- rev(brewer.pal(nclr,"BuPu"))
          cuts <- classIntervals(plotvar, style="fixed", 
               fixedBreaks=c(0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,1))
               colcode <- findColours(cuts, plotclr)
          plot(gadm, col=colcode, border=NA, ylim=c(bbox(gadm)[,1][2], bbox(gadm)[,2][2]),
            xlim=c(bbox(gadm)[,1][1], bbox(gadm)[,2][1]))
            text(min(bbox(gadm)[1]), min(bbox(gadm)[2]), paste("Population Change",x,sep=" "))
          box()
        legend("topleft", legend=c("0-10%","10-20%","20-30%","30-40%","40-50%",
               "50-60%","60-70%","70-80%","80-100%"),
                 fill=attr(colcode, "palette"), cex=0.6, bty="n")   
        ani.pause() 
        },
           img.name="RandPopChange", htmlfile="SimPopChange.html",
           single.opts = "'controls': ['first', 'previous', 'play', 'next', 'last', 'loop', 'speed'], 'delayMin': 0",      
            description=c("Random population change:"))  

I edited the post to provide a more relevant example based on polygon columns.

share|improve this answer
    
Thank you, However, This is the first thing I actually did, starting exploring this question, however it didn't give me the result as I could not understand which expression should be as an argument. –  Ruvin Rafailov Jun 18 '13 at 6:12
    
Oh, I think that is appropriate, will try to optimize for my needs as soon as finished with data preparation. Thank you very much, as soon as it works I will accept an answer. And just the question that arises immediately: is it possible to use spplot here instead of plot, haven't you tried? –  Ruvin Rafailov Jun 18 '13 at 20:10
    
I have editted main question to show my ideas concerning your code, but I am sure I made a number of mistakes as it doesn't work properly. Can you help with this? –  Ruvin Rafailov Jun 18 '13 at 21:48
add comment

The animation that you linked (below) is an animated GIF image.

enter image description here

It is essentially a series of images that are cycled through, which creates the animation effect. Think of it like clicking through a series of slides, one every second or so.

What you need to do in order to create the animation is:

1) Create each individual 'frame' that will be shown.

2) Create the GIF itself. There are several websites that will do this for you:

http://www.createagif.net/

http://makeagif.com/

Most of these websites will allow you to control the size and speed of the animation.

The StackOverflow question you linked to should provide you with everything you need to know to perform this task in R. Notice that you have to install a 3rd party package first.

EDIT: Below is an updated version of the code from the StackOverflow link above since there seems to be a bit of confusion.

jpeg("/tmp/foo%02d.jpg")
for (i in 1:5) {
  my.plot(i)
}      
make.mov <- function(){
     unlink("plot.mpg")
     system("convert -delay 0.5 plot*.jpg plot.mpg")
}

dev.off()

This above code takes each of the individual plots you have created in R and converts them into an animation by looping over each and using ImageMagick, which you must have installed.

share|improve this answer
    
Thank you, but I am a kind have a need of animation to be done inside R without other websites and I really do not understand how this code and idea at stockoverflow works, otherwise I would nor even ask –  Ruvin Rafailov Jun 18 '13 at 6:16
    
I think the stack exchange answer may be a bit confusing because the answer broke the code apart with a block of text. I will edit my answer with an updated version of that code. –  Nick Ochoski Jun 18 '13 at 15:42
    
Thanks for update, but there are still number of problems, which may be stupid and easy,but unfortunately I have no experience with managing them. If you don't mind I'll ask:1) What does jpeg(...) means in this code? as Rstudio gives out a mistake of cannot opening the file 2) Rstudio tells about non-existence of my.plot function, although everything figured out here is installed. May be it's me who operating wrongly, if you can please give some piece of advice. Thanks in advance. –  Ruvin Rafailov Jun 18 '13 at 16:15
add comment

Here is the answer, thanks to Oscar Perpiñán.

library(sp)
library(rgdal)
library(spacetime)
library(animation)
rus <- url("http://www.filefactory.com/file/4h1hb5c1cw7r/n/RUS_adm1_RData")
load(rus)
proj4.str <- CRS("+init=epsg:3413 +lon_0=105")
gadm.prj <- spTransform(gadm, proj4.str)
N <- nrow(gadm.prj)
pols <- geometry(gadm.prj)
nms<-gadm$NAME_1
vals1  <- read.csv2("C:\\unempl11.txt")
ord1 <- match(nms, vals1$region)
vals1 <- vals1[ord1,]

vals2 <- read.csv2("C:\\unempl12.txt")
ord2 <- match(nms, vals2$region)
vals2 <- vals2[ord2,]

nDays <- 2
tt <- seq(as.Date('2011-01-01'), by='year', length=nDays)
vals <- data.frame(unempl=rbind(vals1, vals2)[,-1])

gadmST <- STFDF(pols, time=tt, data=vals)



stplot(gadmST, animate=1, do.repeat=FALSE)

saveHTML(stplot(gadmST, animate=1, do.repeat=FALSE)
, img.name = "unemplan",  htmlfile = "unan.html")
share|improve this answer
    
Ooh, I like the use of the spacetime library! –  Jeffrey Evans Jun 21 '13 at 3:51
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.