好色之徒

2018-09-18 用ggplot2画一朵花吧🌺

2018-09-18  本文已影响28人  iColors

最近浏览,发现有人用R画出了漂亮的曼荼罗图【印度教和佛教中象征宇宙圆形的图】,非常有意思。整理如下


![mandala.png](https://img.haomeiwen.com/i10312333/80c6461ed2de43e6.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

原文见https://github.com/aschinchon/mandalas/blob/master/mandala.R

(1)加载各种包,没有的自行下载

library(ggplot2)
library(dplyr)
library(deldir)

(2)设置绘图参数(可自行更改)

iter=3 # 迭代次数(深度)
points=6 # 绘图点的数目
radius=3.8 # 膨胀/压缩系数

(3)距离中心点的角度

angles=seq(0, 2*pi*(1-1/points), length.out = points)+pi/2

(4)设置起始绘图的中心

df=data.frame(x=0, y=0)

(5)围着中心反复迭代

for (k in 1:iter)
  {
    temp=data.frame()
    for (i in 1:nrow(df))
    {
      data.frame(x=df[i,"x"]+radius^(k-1)*cos(angles), 
                 y=df[i,"y"]+radius^(k-1)*sin(angles)) %>% rbind(temp) -> temp
    }
    df=temp
  }

(6)获得V氏图的区域(Voronoi regions)

df %>%
  select(x,y) %>% 
  deldir(sort=TRUE) %>% 
  .$dirsgs -> data

(7)用ggplot2的 geom_segment绘图

data %>% 
  ggplot() +
  geom_segment(aes(x = x1, y = y1, xend = x2, yend = y2), color="black") +
  scale_x_continuous(expand=c(0,0))+
  scale_y_continuous(expand=c(0,0))+
  coord_fixed() +
  theme(legend.position  = "none",
        panel.background = element_rect(fill="white"),
        panel.border     = element_rect(colour = "black", fill=NA),
        axis.ticks       = element_blank(),
        panel.grid       = element_blank(),
        axis.title       = element_blank(),
        axis.text        = element_blank())->plot

plot  

(8) 保存图片

ggsave("mandala.png", height=5, width=5, units='in', dpi=600)

这是我画出的图,和上面原文给出的有点不一样😓

mandala.png
上一篇 下一篇

猜你喜欢

热点阅读