其他
元旦特刊 | 2020年元旦夜演:用R玩烟花,用心写代码
欢乐过新年,烟花灿九天。
新年伊始,数据Seminar全体人员,祝大家新年快乐,事事如意!本期特刊,我们用R语言绘制出“烟花夜景图”,与大家一同欢度佳节!烟花夜景
R绘制手工烟花
烟花图由Thomas Lin Pedersen开发,主要通过R语言中的ggplot2和gganimate包绘制而成。利用color()函数采样颜色,并控制blast()函数从中心到外围创建片段,然后用ggplot2包绘出静态图形,辅以gganimate包输出动画效果。下面是上图烟花的基本绘图代码,供参考:
##制作烟花(Making Fireworks)
##加载包
library(ggplot2)
library(gganimate)
# Firework colours
colours <- c('lawngreen','gold','white','orchid','royalblue','yellow','orange')
# Produce data for a single blast
blast <- function(n, radius, x0, y0, time) {
u <- runif(n, -1, 1)
rho <- runif(n, 0, 2*pi)
x <- radius * sqrt(1 - u^2) * cos(rho) + x0
y <- radius * sqrt(1 - u^2) * sin(rho) + y0
id <- sample(.Machine$integer.max, n + 1)
data.frame(
x = c(x0, rep(x0, n), x0, x),
y = c(0, rep(y0, n), y0, y),
id = rep(id, 2),
time = c((time - y0) * runif(1), rep(time, n), time, time + radius + rnorm(n)),
colour = c('white', rep(sample(colours, 1), n),
'white', rep(sample(colours, 1), n)),
stringsAsFactors = FALSE
)
}
# Make 20 blasts
n <- round(rnorm(20, 30, 4))
radius <- round(n + sqrt(n))
x0 <- runif(20, -30, 30)
y0 <- runif(20, 40, 80)
time <- runif(20, max = 100)
fireworks <- Map(blast, n = n, radius = radius, x0 = x0, y0 = y0, time = time)
fireworks <- dplyr::bind_rows(fireworks)
# Make Fireworks
ggplot(fireworks) +
geom_path(aes(x = x, y = y, group = id, colour = colour)) +
scale_colour_identity()
ggplot(fireworks) +
geom_point(aes(x, y, colour = colour, group = id), size = 0.5, shape = 20) +
scale_colour_identity() +
coord_fixed(xlim = c(-55, 55), expand = FALSE, clip = 'off') +
theme_void() +
theme(plot.background = element_rect(fill = 'black', colour = NA),
panel.border = element_blank()) +
# Here comes the gganimate code
transition_components(time, exit_length = 20) +
ease_aes(x = 'sine-out', y = 'sine-out') +
shadow_wake(0.05, size = 3, alpha = TRUE, wrap = FALSE,
falloff = 'sine-in', exclude_phase = 'enter') +
exit_recolour(colour = 'black')
左右滑动查看更多
烟花夜景调相
利用调相软件,我们还可以做出更加美观流畅的图形效果:
►一周热文
统计计量丨政策效应评估的四种主流方法(Policy evaluation)
数据Seminar
这里是大数据、分析技术与学术研究的三叉路口
作者:简华(何年华)审阅:杨奇明、谈佳辉编辑:青酱
欢迎扫描👇二维码添加关注