Task 1: Scatter Plot with Regression Line

  1. Load the ggplot2 library.
  2. Load the USArrests dataset into your R session.
  3. Create a scatter plot using ggplot2:
  1. Add a regression line to the scatter plot using geom_smooth() with the method set to “lm” for a linear model.
  2. Customize the plot to improve its aesthetics (optional), such as changing point colors or the theme.
#Practice Assignment: Creating Scatter and Line Plots with ggplot2

# Load the ggplot2 library
library(ggplot2)

# Load the USArrests dataset
data("USArrests")

# Create a scatter plot
ggplot(data = USArrests, aes(x = Murder, y = Assault)) +
  geom_point(color = "blue", size = 3) +  # Scatter plot points
  geom_smooth(method = "lm", se = TRUE, color = "red") +  # Regression line
  labs(title = "Scatter Plot of Assault vs. Murder Rates",
       x = "Murder Rate",
       y = "Assault Rate") +
  theme_minimal()  # Improve plot aesthetics

Task 2: Challenge Question - Line Plot

  1. Calculate the mean of Murder, Assault, and Rape rates for each state and store it in a new column called AverageCrimeRate.
  2. Create a line plot using ggplot2:
  1. Enhance the line plot by adding markers for each data point using geom_point().
  2. Optionally, customize the color of the line and points.
# Add a column for the average crime rate
USArrests$State <- rownames(USArrests)  # Add state names as a column
USArrests$AverageCrimeRate <- rowMeans(USArrests[, c("Murder", "Assault", "Rape")])

# Create a line plot
ggplot(data = USArrests, aes(x = State, y = AverageCrimeRate, group = 1)) +
  geom_line(color = "darkgreen", size = 1) +  # Line
  geom_point(color = "orange", size = 3) +   # Points
  labs(title = "Line Plot of Average Crime Rate by State",
       x = "State",
       y = "Average Crime Rate") +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 90, hjust = 1))  # Rotate x-axis labels