Home > Net >  How to make a graph for a given function in R
How to make a graph for a given function in R

Time:03-27

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.

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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)

CodePudding user response:

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.

  • Related