Line Plots in R: Solved Exercises in Grade 3

Master line plots in R: representing data with ggplot2, interpreting measurements, reading scales, and analyzing data distributions through these 5 detailed exercises.

Solution: Exercises 1 to 3
1 Creating a line plot
Exercise 1
Create a line plot in R to show the heights of 10 students in inches: c(54, 56, 54, 57, 55, 54, 56, 55, 57, 54)
Definition:

Line Plot: A graph that shows frequency of data along a number line using X marks or dots.

R line plot creation method:
  1. Install and load required libraries (ggplot2)
  2. Prepare your data as a vector
  3. Convert to a data frame
  4. Use ggplot() to create the plot
  5. Add geom_point() for individual points
  6. Add geom_line() for connecting lines
54
X
X
X
X
55
X
X
56
X
X
57
X
X
Height of Students (inches)
Step 1: Load required libraries
library(ggplot2)
library(dplyr)
Step 2: Prepare the data
heights <- c(54, 56, 54, 57, 55, 54, 56, 55, 57, 54)
Step 3: Create frequency table and plot
# 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 54: 4 students
Height 55: 2 students
Height 56: 2 students
Height 57: 2 students
Final answer:

The line plot shows that 54-inch tall students are most common (4 students), followed by 55, 56, and 57-inch students (2 each).

Applied rules:

• Data organization: Sort data to identify patterns

• Range identification: Find minimum and maximum values

• Frequency counting: Count how many times each value appears

2 Interpreting a line plot
Exercise 2
Using R, create a line plot for the number of books read by students: c(2, 3, 2, 4, 3, 2, 4, 3, 5, 2)
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?
Definition:

Line Plot Interpretation: Reading the frequency of each value by counting the X marks above each number.

2
X
X
X
X
3
X
X
X
4
X
X
5
X
Number of Books Read
Step 1: Load required libraries
library(ggplot2)
Step 2: Prepare and analyze the data
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)
)
Step 3: Create the line plot
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)
a) 3 students read 3 books
b) 2 books was read by the most students
c) 10 students participated in total
Final answer:

a) 3 students read 3 books
b) 2 books was read by the most students (4 students)
c) 10 students participated in total

Applied rules:

• 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

3 Measuring and plotting
Exercise 3
The students measured the heights of their plants in inches. Results: c(8, 7, 8, 9, 7, 8, 7, 9, 8, 7)
a) Create a line plot showing the plant heights
b) What is the most common height?
c) How many plants were measured?
Definition:

Measurement Data: Numerical data collected by measuring physical quantities like length, weight, or temperature.

7
X
X
X
X
8
X
X
X
X
9
X
X
Height of Plants (inches)
Step 1: Load required libraries
library(ggplot2)
Step 2: Prepare the data
plant_heights <- c(8, 7, 8, 9, 7, 8, 7, 9, 8, 7)
Step 3: Count occurrences and create plot
# 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)
a) Line plot created with 4 plants at 7 inches, 4 plants at 8 inches, 2 plants at 9 inches
b) Most common heights: 7 and 8 inches (tied at 4 plants each)
c) Total plants: 10
Final answer:

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

Applied rules:

• 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 Plots in R Summary
R Line Plots for Data Visualization
Definitions

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.

Core Rules

• 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

R Code Structure
  1. Load libraries: library(ggplot2)
  2. Prepare data: Create vectors or data frames
  3. Process data: Use table() to count frequencies
  4. Create plot: Use ggplot() with geoms
  5. Add details: Titles, labels, themes
  6. Display: The plot is shown automatically
Examples

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")

Tips and Tricks

• 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

Common Mistakes to Avoid

• 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

Key Takeaways

• 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

R Line Plot = Data + Ggplot2
R Visualization Formula
Rule 1
library(ggplot2)
Required library
Rule 2
ggplot(data, aes())
Initialize plot
Rule 3
geom_point() + geom_line()
Add geometries
Tip 1: Use table() for efficient frequency counting.
Tip 2: Convert table output to data frame for ggplot2.
Tip 3: Add geom_text() to show values on the plot.
Tip 4: Use themes for consistent styling.
Solution: Exercises 4 to 5
4 Weight data analysis
Exercise 4
Create an R line plot for backpack weights in pounds: c(12, 15, 12, 16, 14, 12, 15, 14, 16, 12)
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?
Definition:

Weight Data: Measurement data representing mass or weight of objects.

12
X
X
X
X
14
X
X
15
X
X
16
X
X
Weight of Backpacks (pounds)
Step 1: Load required libraries
library(ggplot2)
Step 2: Prepare the data
backpack_weights <- c(12, 15, 12, 16, 14, 12, 15, 14, 16, 12)
Step 3: Count occurrences and create plot
# 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")
a) Line plot created with 4 backpacks at 12 lbs, 2 at 14 lbs, 2 at 15 lbs, 2 at 16 lbs
b) Heaviest backpack weighs 16 pounds
c) 4 backpacks weigh 12 pounds
d) Difference is 4 pounds
Final answer:

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

Applied rules:

• Range calculation: Difference between max and min values

• Frequency analysis: Count occurrences of each value

• Data interpretation: Extract specific information from the plot

5 Time data representation
Exercise 5
Students recorded reading minutes: c(30, 35, 30, 40, 35, 30, 45, 35, 40, 30, 35, 40)
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?
Definition:

Time Data: Measurement data representing duration or time intervals.

30
X
X
X
X
35
X
X
X
X
40
X
X
X
45
X
Minutes Spent Reading
Step 1: Load required libraries
library(ggplot2)
Step 2: Prepare the data
reading_minutes <- c(30, 35, 30, 40, 35, 30, 45, 35, 40, 30, 35, 40)
Step 3: Create the line plot and analyze
# 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")
a) Line plot shows 4 students at 30 mins, 4 students at 35 mins, 3 students at 40 mins, 1 student at 45 mins
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
Final answer:

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

Applied rules:

• Fraction calculation: Part/Whole ratio

• Cumulative counting: Add frequencies for ranges

• Comparison operations: Identify values meeting criteria

R for Data Visualization
R Data Viz = Libraries + Code
R Visualization Concept
Key R libraries:

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.

R workflow:
  1. Load libraries: Get necessary tools
  2. Load data: Create or load your dataset
  3. Process data: Clean and organize as needed
  4. Create visualization: Plot your data
  5. Customize: Add labels, colors, etc.
  6. Display: The plot appears automatically
Tip 1: Use table() for efficient frequency counting in line plots.
Tip 2: Convert table output to data frame for ggplot2 compatibility.
Tip 3: Always add labels and titles for clarity.
Tip 4: Use geom_text() to show frequency values on plots.
Benefits: Elegant plotting system, extensive customization options, publication-ready graphics.
Skills developed: Statistical programming, data analysis, visualization techniques.
R syntax essentials:

• 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.