用R语言,制作动态烟花

用R语言,制作动态烟花🎆

烟花🎆常见,但是用程序代码绘出动态”烟花”却并不常见。

用R语言,制作动态烟花

图 烟花(Fireworks)特效图

如何用R语言,手工绘制烟花动态图呢?

烟花图(Fireworks Plot)由Thomas Lin Pedersen开发,主要通过R语言中的ggplot2和gganimate包绘制而成。利用color()函数采样颜色,并控制blast()函数从中心到外围创建片段,然后用ggplot2包绘出静态图形,辅以gganimate包输出动画效果。

下面是制作烟花R语言所需的代码:

  • *加载包
library(ggplot2)
library(gganimate)
  • *数据准备
Firework colours
colours <- 20 c('lawngreen','gold', 'white','orchid','royalblue','yellow','orange') # produce data for a single blast <- function(n, radius, x0, y0, time) { u runif(n, -1, 1) rho 0, 2*pi) x radius * sqrt(1 - u^2) cos(rho) + x0 y sin(rho) y0 id sample(.machine$integer.max, n data.frame( rep(x0, n), x), rep(y0, y), 2), time="c((time" y0) runif(1), rep(time, time, rnorm(n)), colour="c('white'," rep(sample(colours, 1), 'white', n)), stringsasfactors="FALSE" ) } make blasts round(rnorm(20, 30, 4)) round(n sqrt(n)) runif(20, -30, 30) 40, 80) max="100)" fireworks map(blast, dplyr::bind_rows(fireworks) < code></->
  • *静态制作样式
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(-65, 65), 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')

值得说明,上述代码中,transition_component()函数使所有点独立地遵循自己的轨迹和时间线,ease_aes()函数确保点的速度逐渐变小,shadow_wake()负责每个点之后的轨迹,而exit_recolour()函数确保点逐渐淡入黑色背景。

最后,利用调相软件,还可以做出更加美观流畅的图形效果:

用R语言,制作动态烟花

图 调相烟花图

注:文章代码来源于data-imaginist,仅供各位看官学习交流使用。也可参考2020年元旦夜演:用R玩烟花,用心写代码 文章。

Original: https://blog.csdn.net/weixin_50743123/article/details/120312107
Author: 学习と快乐
Title: 用R语言,制作动态烟花

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/644965/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球