Bar Plot
Exercises
Plot the function \(y = x^2\) on the interval \(x = -10\) to \(x = 10\), then add \(y = -x^2\) on the same plot, using different colors for each curve.
Hint: The first curve has the argument ylim=c(-100,100)
.
Solution:
curve(x^2, from = -10, to = 10,
col = "green",
lwd = 2,
main = expression(paste("Plot of ",y == x^2," and ",y == -x^2)),
xlab = "x", ylab = "y", ylim=c(-100,100))
curve(-x^2, from = -10, to = 10,
col = "purple",
lty = 2, lwd = 2, add = TRUE)
legend("topright",
legend = c(expression(y == x^2), expression(y == -x^2)),
col = c("green", "purple"),
lty = c(1, 2), lwd = 2)
Plot \(y = \sin(x)\) and \(y = \cos(x)\) on the same plot over the interval \(x = 0\) to \(x = 2\pi\), with different line types and colors for each curve.
Solution:
Plot the probability density function of a standard normal distribution, \(y = \frac{1}{\sqrt{2\pi}} e^{-\frac{x^2}{2}}\), over the range \(x = -3\) to \(x = 3\).
Define a custom function, \(f(x) = 3x^3 - 5x^2 + 2x - 4\), and use curve()
to plot it over the range \(x = -3\) to \(x = 3\).
Plot \(y = 2x + 3\) and \(y = -x + 5\) on the same plot over the range \(x = -10\) to \(x = 10\).
Use different line types (e.g., solid and dashed) and colors for each line.
Add a legend indicating which line corresponds to each function.
Solution:
curve(2 * x + 3, from = -10, to = 10,
col = "blue", lty = 1, lwd = 2,
ylab = "y",
main = "Plot of Linear Functions with Legend")
curve(-x + 5, from = -10, to = 10,
col = "red", lty = 2, lwd = 2, add = TRUE)
legend("topright",
legend = c("y = 2x + 3", "y = -x + 5"),
col = c("blue", "red"),
lty = c(1, 2), lwd = 2)
Plot \(y = \sin(x)\) and \(y = \cos(x)\) on the same plot over the interval \(x = 0\) to \(x = 2\pi\).
Use distinct colors and line types for each curve.
Add a legend to show which curve is sine and which is cosine.
Solution:
curve(sin(x), from = 0, to = 2 * pi,
col = "purple", lty = 1, lwd = 2,
ylab = "y",
main = "Sine and Cosine Curves with Legend")
curve(cos(x), from = 0, to = 2 * pi,
col = "orange", lty = 3, lwd = 2, add = TRUE)
legend("topright",
legend = c("sin(x)", "cos(x)"),
col = c("purple", "orange"),
lty = c(1, 3), lwd = 2)
Plot \(y = x^2\) and \(y = e^x\) on the same graph over the range \(x = -2\) to \(x = 2\).
Use different colors and line types for each function.
Add a legend that labels each function appropriately.
Solution:
curve(x^2, from = -2, to = 2,
col = "green", lty = 4, lwd = 2,
ylab = "y",
main = "Quadratic and Exponential Functions with Legend")
curve(exp(x), from = -2, to = 2,
col = "brown", lty = 5, lwd = 2, add = TRUE)
legend("topleft",
legend = c(expression(y == x^2), expression(y == e^x)),
col = c("green", "brown"),
lty = c(4, 5), lwd = 2)