psysky
psysky

Reputation: 3195

How to make a graph for a given function in R

Suppose there is this function sqrt(x^2)+0.9*sqrt(3.3-x^2)*sin(30*pi*x) This function generate plot in the shape of a heart

enter image description here

Is there the way using ggplot2 reproduce this function to get a red heart as output? Thanks you for your help.

Upvotes: 5

Views: 732

Answers (5)

wohlstad
wohlstad

Reputation: 28074

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.

Upvotes: 3

balls69
balls69

Reputation: 1

u can do

f(x)=x^(2/3)+0.85*(4-x^2)^(1/2)*sin(a*pi*x)

Upvotes: 0

Rui Barradas
Rui Barradas

Reputation: 76402

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)

Upvotes: 5

Allan Cameron
Allan Cameron

Reputation: 173793

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"))

enter image description here

Upvotes: 4

PaulS
PaulS

Reputation: 25323

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)

enter image description here

Upvotes: 5

Related Questions