如何在 R 中为给定函数绘制图表

psy*_*sky 5 r ggplot2

假设有这个函数sqrt(x^2)+0.9*sqrt(3.3-x^2)*sin(30*pi*x)这个函数生成一个形状的图heart

在此输入图像描述

有没有办法使用 ggplot2 重现此函数来获得红色heart作为输出?感谢您的帮助。

Pau*_*ulS 5

一个可能的解决方案:

f <-  function(x) sqrt(x^2)+0.9*sqrt(3.3-x^2)*sin(30*(pi)*x)

ggplot() +
  xlim(-2, 2) +
  geom_function(fun = f, color="red") + 
  theme(aspect.ratio=0.85)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


Rui*_*das 5

还有另一个解决方案。这个带有函数的解析表达式。

library(ggplot2)

f <- function(x) abs(x)^(2/3)+0.9*sqrt(3.3-x^2)*sin(18*pi*x)

expr <- "y == abs(x)^frac(2, 3) + 0.9 * sqrt(3.3 - x^2) ~ sin(18 * pi * x)"

ggplot() + 
  geom_function(fun = f, xlim = c(-sqrt(3.3), sqrt(3.3)), n = 1e4, color = "red") +
  annotate("text", x = 0, y = 3, colour = "white",
            label = expr,
            hjust = 0.5,
            parse = TRUE) +
  ylim(-2, 3.5) +
  theme(
    panel.background = element_rect(colour = "black", fill = "black"),
    panel.grid = element_blank(),
    aspect.ratio = 4/3
  )
Run Code Online (Sandbox Code Playgroud)

由reprex 包(v2.0.1)创建于 2022-03-26


All*_*ron 4

如果直接按照预定义的顺序进行计算,您将获得更好的分辨率。另外,公式不太对,所以我修改了一下:

heart <- function(x) abs(x)^(2/3) + 0.9 * sqrt(3.3 - x^2) * sin(18 * pi * x)

df <- data.frame(x = seq(-sqrt(3.3), sqrt(3.3), length = 3000),
                 y = heart(seq(-sqrt(3.3), sqrt(3.3), length = 3000)))


ggplot(df, aes(x, y)) + 
  geom_line(size = 1, colour = "red") +
  scale_x_continuous(limits = c(-2, 2)) +
  coord_equal() +
  theme_void() +
  theme(plot.background = element_rect(fill = "#400000"))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述