akhi07rx

4 min read

Trying to Understand R


I’ve been trying to learn a bit of R lately.

Coming from Python, R feels incredibly fast at doing certain things, especially anything related to statistics, data analysis, or plotting. At the same time, it also feels a little intimidating. Python usually reads like a series of instructions, while R often feels like it expects you to already know how it thinks.

While experimenting with plots, I came across a simple piece of code that generates a flower-like pattern using trigonometric functions.

Petals in R

The entire plot is created with just a few lines of R:

n_petals <- 16
theta <- seq(0, 2*pi, length.out = 1000)

radius <- sin(n_petals * theta)

x <- radius * cos(theta)
y <- radius * sin(theta)

plot(x, y, type = "l", xlab = "X", ylab = "Y", main = "Petals in R")

I spent more time than I’d like to admit wondering why n_petals = 16 was drawing 32 petals. Turns out that’s just how rose curves work. Even values of n produce 2n petals, while odd values produce n. At least the math wasn’t wrong. My assumption was. :)

P.S. I’m terrible at math, so there’s a good chance I’ll end up back here in a few months wondering why there are 32 petals again.

Since Python is what I’m most comfortable with, I ended up rewriting it there as well.

import numpy as np
import matplotlib.pyplot as plt

n_petals = 16
theta = np.linspace(0, 2 * np.pi, 1000)

radius = np.sin(n_petals * theta)

x = radius * np.cos(theta)
y = radius * np.sin(theta)

plt.figure(figsize=(6, 6))
plt.plot(x, y)
plt.xlabel("X")
plt.ylabel("Y")
plt.title("Petals in Python")
plt.axis("equal")
plt.show()

While looking into it, I also found out that this is actually called a rose curve 11A rose curve, also called Grandi’s rose or the multifolium, is a curve which has the shape of a petalled flower. This curve was named rhodonea by the Italian mathematician Guido Grandi between 1723 and 1728 because it resembles a rose. , and Matplotlib can draw it directly using polar coordinates.

import numpy as np
import matplotlib.pyplot as plt

n_petals = 16
theta = np.linspace(0, 2 * np.pi, 1000)
r = np.sin(n_petals * theta)

ax = plt.subplot(projection="polar")
ax.plot(theta, r)
ax.set_title("Rose Curve")
plt.show()

I’m still trying to get comfortable with R. Most of the time I find myself translating what I’m looking at into Python just to understand it better.

Still, it’s fun stumbling across things like this. You change a number, run the code, and suddenly there’s a flower on the screen.

:)