Line Plot: A graph that shows frequency of data along a number line using X marks or dots.
- Install and load required libraries (ggplot2)
- Prepare your data as a vector
- Convert to a data frame
- Use ggplot() to create the plot
- Add geom_point() for individual points
- Add geom_line() for connecting lines
library(ggplot2)
library(dplyr)
heights <- c(54, 56, 54, 57, 55, 54, 56, 55, 57, 54)
# Count occurrences of each height
height_freq <- table(heights)
height_df <- data.frame(
height = as.numeric(names(height_freq)),
count = as.numeric(height_freq)
)
# Create the line plot
ggplot(height_df, aes(x = height, y = count)) +
geom_point(size = 4, color = "blue") +
geom_line(color = "blue", size = 1) +
labs(
title = "Heights of Students Line Plot",
x = "Height (inches)",
y = "Number of Students"
) +
theme_minimal() +
scale_x_continuous(breaks = height_df$height)
Height 55: 2 students
Height 56: 2 students
Height 57: 2 students
The line plot shows that 54-inch tall students are most common (4 students), followed by 55, 56, and 57-inch students (2 each).
• Data organization: Sort data to identify patterns
• Range identification: Find minimum and maximum values
• Frequency counting: Count how many times each value appears
Answer these questions:
a) How many students read 3 books?
b) Which number of books was read by the most students?
c) How many students participated in total?
Line Plot Interpretation: Reading the frequency of each value by counting the X marks above each number.
library(ggplot2)
books_read <- c(2, 3, 2, 4, 3, 2, 4, 3, 5, 2)
book_freq <- table(books_read)
book_df <- data.frame(
books = as.numeric(names(book_freq)),
count = as.numeric(book_freq)
)
ggplot(book_df, aes(x = books, y = count)) +
geom_point(size = 5, color = "red") +
geom_line(color = "red", size = 1.2) +
geom_text(aes(label = count), vjust = -0.5, size = 4) +
labs(
title = "Books Read by Students",
x = "Number of Books Read",
y = "Number of Students"
) +
theme_minimal() +
scale_x_continuous(breaks = book_df$books)
b) 2 books was read by the most students
c) 10 students participated in total
a) 3 students read 3 books
b) 2 books was read by the most students (4 students)
c) 10 students participated in total
• Frequency counting: Count X marks above each number
• Mode identification: The value with the most X marks is the mode
• Total calculation: Sum all X marks to find total participants
a) Create a line plot showing the plant heights
b) What is the most common height?
c) How many plants were measured?
Measurement Data: Numerical data collected by measuring physical quantities like length, weight, or temperature.
library(ggplot2)
plant_heights <- c(8, 7, 8, 9, 7, 8, 7, 9, 8, 7)
# Count occurrences of each height
height_counts <- table(plant_heights)
height_df <- data.frame(
height = as.numeric(names(height_counts)),
count = as.numeric(height_counts)
)
# Create the line plot
ggplot(height_df, aes(x = height, y = count)) +
geom_point(size = 6, color = "green") +
geom_line(color = "green", size = 1.5) +
geom_text(aes(label = count), vjust = -0.5, size = 5) +
labs(
title = "Plant Heights Line Plot",
x = "Plant Height (inches)",
y = "Number of Plants"
) +
theme_classic() +
scale_x_continuous(breaks = height_df$height)
b) Most common heights: 7 and 8 inches (tied at 4 plants each)
c) Total plants: 10
a) Line plot shows 4 plants at 7 inches, 4 plants at 8 inches, 2 plants at 9 inches
b) Most common heights are 7 inches and 8 inches (each with 4 plants)
c) 10 plants were measured in total
• Measurement precision: Record exact values when measuring
• Frequency analysis: Multiple values may have the same frequency
• Data verification: Ensure total X marks equals total items measured
Line Plot: A special kind of graph that uses X marks to show how often each number appears in a set of data.
Ggplot2: R package for creating elegant and complex visualizations.
Data: Information we collect, like heights, weights, or test scores.
Frequency: How many times something happens or appears.
Mode: The number that appears most often in a data set.
Data Frame: R structure for storing tabular data.
• Always load ggplot2 library with library(ggplot2)
• Use ggplot() to initialize the plot
• Use geom_point() to create individual points
• Use geom_line() to connect points
• Use labs() to add titles and labels
- Load libraries: library(ggplot2)
- Prepare data: Create vectors or data frames
- Process data: Use table() to count frequencies
- Create plot: Use ggplot() with geoms
- Add details: Titles, labels, themes
- Display: The plot is shown automatically
Simple Example:
library(ggplot2)
data <- c(1, 2, 2, 3)
freq_table <- table(data)
df <- data.frame(value = as.numeric(names(freq_table)),
count = as.numeric(freq_table))
ggplot(df, aes(x = value, y = count)) +
geom_point() + geom_line()
Advanced Example:
library(ggplot2)
data <- c(5, 6, 5, 7, 5)
freq_table <- table(data)
df <- data.frame(value = as.numeric(names(freq_table)),
count = as.numeric(freq_table))
ggplot(df, aes(x = value, y = count)) +
geom_col(fill = "blue", alpha = 0.7) +
labs(title = "My Plot", x = "Values", y = "Counts")
• Tip 1: Use table() to quickly count frequencies
• Tip 2: Convert table results to data frames for plotting
• Tip 3: Use geom_text() to show count values on the plot
• Tip 4: Customize appearance with themes and colors
• Tip 5: Use scale_x_continuous() to control x-axis breaks
• Forgetting to load the ggplot2 library
• Not converting table results to a data frame
• Using incorrect variable names in aes()
• Missing quotes around string arguments
• Not handling data types properly
• R makes creating line plots elegant with ggplot2
• Line plots help visualize frequency distributions
• The mode is the highest point on the line plot
• R allows extensive customization of appearance
• Data processing in R is efficient and flexible
a) Create a line plot for the backpack weights
b) How much does the heaviest backpack weigh?
c) How many backpacks weigh 12 pounds?
d) What is the difference between the heaviest and lightest backpacks?
Weight Data: Measurement data representing mass or weight of objects.
library(ggplot2)
backpack_weights <- c(12, 15, 12, 16, 14, 12, 15, 14, 16, 12)
# Count occurrences
weight_freq <- table(backpack_weights)
weight_df <- data.frame(
weight = as.numeric(names(weight_freq)),
count = as.numeric(weight_freq)
)
# Create the line plot
ggplot(weight_df, aes(x = weight, y = count)) +
geom_point(size = 5, color = "orange") +
geom_line(color = "orange", size = 1.2) +
geom_text(aes(label = count), vjust = -0.5, size = 4) +
labs(
title = "Backpack Weights Line Plot",
x = "Backpack Weight (pounds)",
y = "Number of Backpacks"
) +
theme_minimal() +
scale_x_continuous(breaks = weight_df$weight)
# Answer the questions
heaviest_weight <- max(backpack_weights)
lightest_weight <- min(backpack_weights)
weight_12_count <- sum(backpack_weights == 12)
weight_difference <- heaviest_weight - lightest_weight
cat("Heaviest backpack:", heaviest_weight, "pounds\n")
cat("Backpacks weighing 12 lbs:", weight_12_count, "\n")
cat("Difference between heaviest and lightest:", weight_difference, "pounds\n")
b) Heaviest backpack weighs 16 pounds
c) 4 backpacks weigh 12 pounds
d) Difference is 4 pounds
a) Line plot shows 4 backpacks at 12 lbs, 2 at 14 lbs, 2 at 15 lbs, 2 at 16 lbs
b) The heaviest backpack weighs 16 pounds
c) 4 backpacks weigh 12 pounds
d) The difference between heaviest and lightest is 4 pounds
• Range calculation: Difference between max and min values
• Frequency analysis: Count occurrences of each value
• Data interpretation: Extract specific information from the plot
a) Create a line plot of the reading times
b) What is the most common reading time?
c) How many students read for 35 minutes or more?
d) What fraction of students read for exactly 30 minutes?
Time Data: Measurement data representing duration or time intervals.
library(ggplot2)
reading_minutes <- c(30, 35, 30, 40, 35, 30, 45, 35, 40, 30, 35, 40)
# Count occurrences
minute_freq <- table(reading_minutes)
minute_df <- data.frame(
minutes = as.numeric(names(minute_freq)),
count = as.numeric(minute_freq)
)
# Create the line plot
ggplot(minute_df, aes(x = minutes, y = count)) +
geom_point(size = 5, color = "purple") +
geom_line(color = "purple", size = 1.2) +
geom_text(aes(label = count), vjust = -0.5, size = 4) +
labs(
title = "Reading Time Line Plot",
x = "Minutes Spent Reading",
y = "Number of Students"
) +
theme_classic() +
scale_x_continuous(breaks = minute_df$minutes)
# Answer the questions
total_students <- length(reading_minutes)
most_common_time <- as.numeric(names(which.max(minute_freq)))
students_35_or_more <- sum(reading_minutes >= 35)
students_30_exact <- sum(reading_minutes == 30)
fraction_30 <- students_30_exact / total_students
cat("Most common reading time:", most_common_time, "minutes (", minute_freq[as.character(most_common_time)], "students)\n")
cat("Students reading 35+ minutes:", students_35_or_more, "\n")
cat("Fraction reading exactly 30 minutes:", fraction_30, "(", students_30_exact, "/", total_students, ")\n")
b) Most common times: 30 and 35 minutes (tied at 4 students each)
c) 8 students read for 35 minutes or more
d) 1/3 of students read for exactly 30 minutes
a) Line plot created with 4 students at 30 mins, 4 at 35 mins, 3 at 40 mins, 1 at 45 mins
b) Most common reading times are 30 and 35 minutes (4 students each)
c) 8 students read for 35 minutes or more
d) 1/3 of students (4 out of 12) read for exactly 30 minutes
• Fraction calculation: Part/Whole ratio
• Cumulative counting: Add frequencies for ranges
• Comparison operations: Identify values meeting criteria
Ggplot2: The grammar of graphics for creating elegant plots.
Dplyr: For data manipulation and analysis.
Stats: Built-in statistics functions.
Base R: Built-in functions like table() for frequency counting.
- Load libraries: Get necessary tools
- Load data: Create or load your dataset
- Process data: Clean and organize as needed
- Create visualization: Plot your data
- Customize: Add labels, colors, etc.
- Display: The plot appears automatically
• Library: library(ggplot2)
• Plot: ggplot(data, aes(x, y))
• Geoms: geom_point(), geom_line()
• Labels: labs(title, x, y)
• Frequency: table(data)
Questions & Answers
Question: Why do I need to convert table() output to a data frame for ggplot2?
Answer: Great question! Here's why:
- ggplot2 format: ggplot2 expects data in a specific data frame format
- table() output: Returns a named vector, not a data frame
- Conversion needed: Data frames have columns that ggplot2 can map to aesthetics
The conversion creates separate columns for x-values (heights) and y-values (counts) that ggplot2 can use for mapping.
Example: table(c(1,1,2)) returns a vector with names "1" and "2", counts 2 and 1. Converting to df creates x and y columns.
Question: What's the difference between geom_point() and geom_line() in R?
Answer: Here's the difference:
- geom_point(): Creates individual points (dots) at each data location
- geom_line(): Creates lines connecting the points in sequence
- Together they show both individual data points and trends
For line plots showing frequency, you typically use both to show individual occurrences AND the relationship between values.
You can use just one depending on your needs, but both provide the clearest visualization.
Question: Can I use other packages besides ggplot2 for line plots in R?
Answer: Yes, there are several alternatives:
- Base R plot: plot(x, y, type = "b") for basic line plots
- Lattice: xyplot() for conditioning plots
- Plotly: Interactive plots with plot_ly()
- Highcharter: R wrapper for Highcharts
However, ggplot2 is the most widely used and feature-rich, making it the best starting point for learning data visualization in R.
For basic line plots, ggplot2 provides the most flexibility and control.