plot(cars)
install.packages("tidyverse")
## Installing package into '/cloud/lib/x86_64-pc-linux-gnu-library/4.3'
## (as 'lib' is unspecified)
#Load the mtcars dataset (built into R)
data_mtcars <- mtcars
#View the first few rows to understand the data
head(data_mtcars)
#Convert 'am' (transmission type) and 'cyl' (number of cylinders) to factors for categorical plotting
data_mtcars$am <- as.factor(data_mtcars$am)
data_mtcars$cyl <- as.factor(data_mtcars$cyl)
head(data_mtcars)
library(ggplot2)
#Create a scatter plot of car weight vs. miles per gallon, colored by cylinder count
ggplot(data_mtcars, aes(x = wt, y = mpg, color = cyl)) +
geom_point() + #Add points to the plot
labs(title = "Miles Per Gallon vs Weight", x = "Weight (1000 lbs)", y = "Miles Per Gallon") # Add plot labels
library(dplyr)
##
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
##
## filter, lag
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
library(ggplot2)
#Create a line graph of ordered mpg by the row number
data_mtcars_line <- data_mtcars %>% mutate(index = row_number())
ggplot(data_mtcars_line, aes(x = index, y = mpg)) +
geom_line() +
labs(
title = "Miles Per Gallon by Index",
x = "Index",
y = "Miles Per Gallon"
)
#Create a horizontal bar chart of the average horsepower grouped by cylinder count
hp_by_cyl <- data_mtcars %>% group_by(cyl) %>% summarize(avg_hp = mean(hp)) # Calculate average horsepower for each cylinder group
ggplot(hp_by_cyl, aes(y = cyl, x = avg_hp)) +
geom_bar(stat = 'identity') + # Create bars based on the calculated averages
labs(title = "Average HP by Cylinder Count", y = "Cylinder Count", x = "Average Horsepower") # Add plot labels
library(dplyr)
library(tidyr)
library(ggplot2)
# Create a stacked bar chart of average mpg, disp, hp, and wt grouped by cyl
bar_data_mtcars <- data_mtcars %>%
group_by(cyl) %>%
summarize(
mpg = mean(mpg),
disp = mean(disp),
hp = mean(hp),
wt = mean(wt)
) %>%
pivot_longer(
cols = c(mpg, disp, hp, wt),
names_to = "Measurement",
values_to = "Average"
)
ggplot(bar_data_mtcars, aes(x = factor(cyl), fill = Measurement, y = Average)) +
geom_bar(stat = "identity") +
labs(
title = "Average Measurements by Cylinder Count",
x = "Cylinder Count",
y = "Average Measurement"
)
```