Task 1: Scatter Plot with Regression Line
#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
# 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