'How to make a graph for a given function in R
Solution 1:[1]
You will get better resolution if you directly calculate along a predefined sequence. Also, the formula is not quite right, so I have amended it:
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"))
Solution 2:[2]
A possible solution:
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)
Solution 3:[3]
Yet another solution. This one with the function's analytic expression.
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
)

Created on 2022-03-26 by the reprex package (v2.0.1)
Solution 4:[4]
I am not familiar with R that much. But the function you mentioned:
sqrt(x^2)+0.9*sqrt(3.3-x^2)*sin(30*pi*x)
is not the one in the image.
It should be:
(x^2)^(1/3)+0.9*sqrt(3.3-x^2)*sin(30*pi*x)
I.e. use the 3rd root of (x^2), not the 2nd root.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Allan Cameron |
| Solution 2 | |
| Solution 3 | |
| Solution 4 | wohlstad |



