Uncategorized

Momento R do Dia

happy2015

Ok, eu apenas copiei os comandos deste ótimo postEntretanto, é preciso carregar os pacotes primeiro. Bem, são eles: ggplot2, animation e colorspace. De forma que temos, então:

library(ggplot2)
library(animation)
library(colorspace)

# since here, a simple copy 
# from: http://rforpublichealth.blogspot.com.br/2014/12/animations-and-gifs-using-ggplot2.html
#create dataset
happy2015<-data.frame(x=rnorm(500, 0, 1.5), y=rnorm(500, 0, 1.5), z=rnorm(500,0,1.5))

#create objects to hold the letters, colors, and x and y coordinates that we will scroll through
sign<-c("H","A","P","P","Y","2","0","1","5","!!")
colors <- rainbow_hcl(10, c=300)
xcoord<-rep(c(-2, -1, 0, 1, 2),2)
ycoord<-c(2, 1.7, 2.1, 1.5, 2, -.5, 0, -1, -.8, -.7)

#set up the theme in an object (get rid of axes, grids, and legend)
theme.both<- theme(legend.position="none", 
                   panel.background = element_blank(),
                   axis.ticks = element_blank(),
                   axis.line = element_blank(), 
                   axis.text.x = element_blank(), 
                   axis.text.y = element_blank(),
                   plot.background = element_rect(fill = "black"),
                   panel.grid.major = element_blank(), 
                   panel.grid.minor = element_blank())

#plot the first letter (set index=1 to get the first element of color, letter, and coordinates)
index<-1
ggplot(happy2015, aes(x, y, alpha = z, color=z)) + 
  geom_point(alpha=0.2) + labs(title="", x="", y="") + 
  theme.both + 
  scale_colour_gradient(low = "white", high="lightblue")+
  annotate("text", x=xcoord[index], y=ycoord[index], size=15, label=sign[index], color=colors[index])

#set up function to create a new dataset, plot it, and annotate it by an index argument
draw.a.plot<-  function(index){
  
  #make up a new dataframe
  happy2015<-data.frame(x=rnorm(500, 0, 1.5), y=rnorm(500, 0, 1.5), z=rnorm(500,0,1.5))
  
  #plot according to the index passed
  g<-ggplot(happy2015, aes(x, y, alpha = z, color=z)) + 
    geom_point(alpha=0.2) + labs(title="", x="", y="") + 
    theme.both + 
    scale_colour_gradient(low = "white", high="lightblue")+
    annotate("text", x=xcoord[index], y=ycoord[index], size=15, label=sign[index], color=colors[index])
  
  #print out the plot
  print(g)
}

#set up function to loop through the draw.a.plot() function
loop.animate <- function() {
  lapply(1:length(sign), function(i) {
    draw.a.plot(i)
  })
}

#save the images into a GIF
saveGIF(loop.animate(), interval = .5, movie.name="happy2015.gif")

Gostou?