library(ggplot2)Program 7
Develop a function in R to plot a function curve based on a mathematical equation provided as input, with different curve styles for each group, using ggplot2.
Step 1: Load the required library
Step 2: Create data for the functions
# Create a sequence of x values ranging from -2pi to 2pi
x <- seq(-2*pi, 2*pi, length.out = 500)
# Evaluate sin(x) and cos(x) over the x range
y1 <- sin(x)
y2 <- cos(x)
# Combine data into one data frame
df <- data.frame(
x = rep(x, 2), # Repeat x values for both functions
y = c(y1, y2), # Combine y values: first sin(x, then cos(x))
group = rep(c("sin(x)", "cos(x)"), each = length(x)) # Label each row by function
)Step 3: Plot the Function Curves
Step 3.1: Initialize the ggplot Object
# Start building the ggplot using the data frame and aesthetics
p <- ggplot(df, aes(x = x, y = y, color = group, linetype = group))Step 3.2: Add the Line Geometry
# Add smooth lines to represent each function curve
p <- p + geom_line(size = 1.2)Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
ℹ Please use `linewidth` instead.
Step 3.3: Add Plot Labels
# Add title, axis labels, and legends
P <- p + labs(title = "Function Curves: sin(x) and cos(x)",
x = "x",
y = "y = f(x)",
color = "function",
linetype = "Function")Step 3.4: Apply a Clean Theme
# Use a clean and simple background theme
p <- p + theme_minimal()
p