前言
在母亲节这天用R画一朵这样的花送给妈妈或许是一个不错的选择。下面将介绍详细步骤。
首先需要安装这些包
- ggplot2
- tidyverse
- mvtnorm
如果没有,请先安装
确保已安装好上述包之后,载入包
library(ggplot2)
library(tidyverse)
library(mvtnorm)
画出花的茎
p <- ggplot() +
coord_equal(1, c(-4, 2), c(-7, 3)) +
geom_curve(aes(x = -1, y = -7, xend = 0, yend = 0),
ncp = 1000, curvature = -0.3, size = 1,
color = "olivedrab3")
p #查看
画出花的叶子
#定义画叶子需要的函数
geom_leaf <- function(x, xend, f, xoffset = 0, yoffset = 0,
xflip = 1, yflip = 1, ...) {
.x <- seq(x, xend, length.out = 100)
.y <- f(.x)
df <- tibble(x = c(.x, .y), y = c(.y, .x))
df$x <- xflip * df$x + xoffset
df$y <- yflip * df$y + yoffset
geom_polygon(aes(x = x, y = y), data = df, ...)
}
#画出叶子
p <- p +
geom_leaf(0, 2, f, -1.6, -4.5, 1,
fill = "olivedrab3", color = "palegreen") +
geom_leaf(0, 2, f, -1.6, -5, -1,
fill = "olivedrab3", color = "palegreen")
#查看效果
p
画出花瓣
#依旧先定义好函数
f <- function(x) x^2 / 2
geom_rose <- function(n, mean = c(0, 0), ...) {
.x <- mvtnorm::rmvnorm(n, mean)
df <- tibble(x = .x[, 1], y = .x[, 2])
list(
stat_density_2d(
aes(x = x, y = y, fill = stat(level)), data = df,
geom = "polygon", show.legend = FALSE, color = "grey80"),
scale_fill_gradient2(...)
)
}
#最后一步,画出完整的图像
p +
geom_rose(1000, mean = c(0, 0),
low = "red", mid = "purple", high = "pink",
midpoint = 0.075) +
theme_void()
如果学到了,就赶紧行动吧!