Line Plots in Python: Solved Exercises in Grade 3

Master line plots in python: representing data with matplotlib, 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 Python to show the heights of 10 students in inches: [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.

Python line plot creation method:
  1. Import matplotlib.pyplot
  2. Prepare your data as a list
  3. Use plt.plot() to create the line plot
  4. Add labels and title
  5. Display the plot with plt.show()
54
X
X
X
X
55
X
X
56
X
X
57
X
X
Height of Students (inches)
Step 1: Import required libraries
import matplotlib.pyplot as plt
import numpy as np
Step 2: Prepare the data
heights = [54, 56, 54, 57, 55, 54, 56, 55, 57, 54]
Step 3: Create the line plot
# Count occurrences of each height
unique_heights = sorted(set(heights))
counts = [heights.count(h) for h in unique_heights]

# Create the plot
plt.figure(figsize=(10, 6))
plt.scatter(unique_heights, counts, s=100, alpha=0.7)
plt.plot(unique_heights, counts, marker='o', linestyle='-', linewidth=2)

# Add labels and title
plt.xlabel('Height (inches)')
plt.ylabel('Number of Students')
plt.title('Heights of Students Line Plot')
plt.grid(True, alpha=0.3)

# Show the plot
plt.show()
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 Python, create a line plot for the number of books read by students: [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: Import required libraries
import matplotlib.pyplot as plt
from collections import Counter
Step 2: Prepare and analyze the data
books_read = [2, 3, 2, 4, 3, 2, 4, 3, 5, 2]
counter = Counter(books_read)
unique_values = sorted(counter.keys())
frequencies = [counter[val] for val in unique_values]
Step 3: Create the line plot
plt.figure(figsize=(10, 6))
plt.plot(unique_values, frequencies, marker='o', linestyle='-', linewidth=2, markersize=8)
plt.scatter(unique_values, frequencies, s=150, zorder=5)

plt.xlabel('Number of Books Read')
plt.ylabel('Number of Students')
plt.title('Books Read by Students')
plt.grid(True, alpha=0.3)

# Add value labels on top of each point
for i, freq in enumerate(frequencies):
    plt.text(unique_values[i], freq + 0.1, str(freq), ha='center', va='bottom')

plt.show()
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: [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: Import required libraries
import matplotlib.pyplot as plt
import numpy as np
Step 2: Prepare the data
plant_heights = [8, 7, 8, 9, 7, 8, 7, 9, 8, 7]
Step 3: Count occurrences and create plot
# Count occurrences of each height
height_counts = {}
for height in plant_heights:
    height_counts[height] = height_counts.get(height, 0) + 1

# Sort by height
sorted_heights = sorted(height_counts.keys())
counts = [height_counts[h] for h in sorted_heights]

# Create the line plot
plt.figure(figsize=(10, 6))
plt.plot(sorted_heights, counts, marker='o', linestyle='-', linewidth=2, markersize=10, color='green')
plt.scatter(sorted_heights, counts, s=200, color='red', zorder=5)

plt.xlabel('Plant Height (inches)')
plt.ylabel('Number of Plants')
plt.title('Plant Heights Line Plot')
plt.grid(True, alpha=0.3)

# Add count labels
for i, count in enumerate(counts):
    plt.text(sorted_heights[i], count + 0.1, str(count), ha='center', va='bottom', fontsize=12)

plt.show()
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 Python Summary
Python 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.

Matplotlib: Python library for creating static, animated, and interactive 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.

Counter: Python tool for counting hashable objects.

Core Rules

• Always import matplotlib.pyplot as plt

• Use plt.plot() to create line connections

• Use plt.scatter() to create individual points

• Add labels and titles for clarity

• Use plt.show() to display the plot

Python Code Structure
  1. Import libraries: import matplotlib.pyplot as plt
  2. Prepare data: Create lists or arrays with your data
  3. Process data: Count frequencies if needed
  4. Create plot: Use plt.plot() and plt.scatter()
  5. Add details: Labels, title, grid
  6. Show plot: Use plt.show()
Examples

Simple Example:

import matplotlib.pyplot as plt
data = [1, 2, 2, 3]
unique_vals = sorted(set(data))
counts = [data.count(v) for v in unique_vals]
plt.plot(unique_vals, counts)
plt.show()

Advanced Example:

import matplotlib.pyplot as plt
from collections import Counter
data = [5, 6, 5, 7, 5]
counter = Counter(data)
plt.bar(counter.keys(), counter.values())
plt.show()

Tips and Tricks

• Tip 1: Use Counter from collections module to count occurrences efficiently

• Tip 2: Combine plt.plot() and plt.scatter() for both line and points

• Tip 3: Use plt.grid(True) to add a grid for better readability

• Tip 4: Add text annotations with plt.text() to show values

• Tip 5: Use figsize parameter to control plot size

Common Mistakes to Avoid

• Forgetting to import matplotlib.pyplot

• Not calling plt.show() to display the plot

• Using incorrect data types for plotting

• Missing axis labels and titles

• Not sorting data before plotting

Key Takeaways

• Python makes creating line plots easy with matplotlib

• Line plots help visualize frequency distributions

• The mode is the highest point on the line plot

• Python allows customization of appearance

• Data processing in Python is efficient

Python Line Plot = Data + Matplotlib
Python Visualization Formula
Rule 1
import matplotlib.pyplot
Required import
Rule 2
plt.plot(data)
Create the line
Rule 3
plt.show()
Display the plot
Tip 1: Use Counter from collections for efficient frequency counting.
Tip 2: Combine scatter and line plots for best visualization.
Tip 3: Add grid and labels for better readability.
Tip 4: Use figsize to control plot dimensions.
Solution: Exercises 4 to 5
4 Weight data analysis
Exercise 4
Create a Python line plot for backpack weights in pounds: [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: Import required libraries
import matplotlib.pyplot as plt
from collections import Counter
Step 2: Prepare the data
backpack_weights = [12, 15, 12, 16, 14, 12, 15, 14, 16, 12]
Step 3: Count occurrences and create plot
# Count occurrences
weight_counter = Counter(backpack_weights)
sorted_weights = sorted(weight_counter.keys())
counts = [weight_counter[w] for w in sorted_weights]

# Create the line plot
plt.figure(figsize=(10, 6))
plt.plot(sorted_weights, counts, marker='o', linestyle='-', linewidth=2, markersize=10)
plt.scatter(sorted_weights, counts, s=200, color='orange', zorder=5)

plt.xlabel('Backpack Weight (pounds)')
plt.ylabel('Number of Backpacks')
plt.title('Backpack Weights Line Plot')
plt.grid(True, alpha=0.3)

# Add count labels
for i, count in enumerate(counts):
    plt.text(sorted_weights[i], count + 0.1, str(count), ha='center', va='bottom', fontsize=12)

plt.show()

# Answer the questions
heaviest_weight = max(backpack_weights)
lightest_weight = min(backpack_weights)
weight_12_count = weight_counter[12]
weight_difference = heaviest_weight - lightest_weight

print(f"Heaviest backpack: {heaviest_weight} pounds")
print(f"Backpacks weighing 12 lbs: {weight_12_count}")
print(f"Difference between heaviest and lightest: {weight_difference} pounds")
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: [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: Import required libraries
import matplotlib.pyplot as plt
from collections import Counter
Step 2: Prepare the data
reading_minutes = [30, 35, 30, 40, 35, 30, 45, 35, 40, 30, 35, 40]
Step 3: Create the line plot and analyze
# Count occurrences
minute_counter = Counter(reading_minutes)
sorted_minutes = sorted(minute_counter.keys())
counts = [minute_counter[m] for m in sorted_minutes]

# Create the line plot
plt.figure(figsize=(10, 6))
plt.plot(sorted_minutes, counts, marker='o', linestyle='-', linewidth=2, markersize=10, color='purple')
plt.scatter(sorted_minutes, counts, s=200, color='red', zorder=5)

plt.xlabel('Minutes Spent Reading')
plt.ylabel('Number of Students')
plt.title('Reading Time Line Plot')
plt.grid(True, alpha=0.3)

# Add count labels
for i, count in enumerate(counts):
    plt.text(sorted_minutes[i], count + 0.1, str(count), ha='center', va='bottom', fontsize=12)

plt.show()

# Answer the questions
total_students = len(reading_minutes)
most_common_time = max(minute_counter, key=minute_counter.get)
students_35_or_more = sum(count for minute, count in minute_counter.items() if minute >= 35)
students_30_exact = minute_counter[30]
fraction_30 = students_30_exact / total_students

print(f"Most common reading time: {most_common_time} minutes ({minute_counter[most_common_time]} students)")
print(f"Students reading 35+ minutes: {students_35_or_more}")
print(f"Fraction reading exactly 30 minutes: {fraction_30} ({students_30_exact}/{total_students})")
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

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

Matplotlib: The foundational plotting library for Python.

Pandas: For data manipulation and analysis.

NumPy: For numerical computations.

Seaborn: For statistical data visualization.

Python workflow:
  1. Import 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: Show the final plot
Tip 1: Use Counter for efficient frequency counting in line plots.
Tip 2: Combine scatter and line plots for comprehensive visualization.
Tip 3: Always add labels and titles for clarity.
Tip 4: Use grid for better readability of plots.
Benefits: Automates data visualization, allows for complex analysis, customizable outputs.
Skills developed: Programming logic, data analysis, visualization techniques.
Python syntax essentials:

• Import: import matplotlib.pyplot as plt

• Plot: plt.plot(x_data, y_data)

• Scatter: plt.scatter(x_data, y_data)

• Show: plt.show()

• Labels: plt.xlabel(), plt.ylabel(), plt.title()

Questions & Answers

Question: Why do I need to use both plt.plot() and plt.scatter() for line plots in Python?

Answer: Great question! Using both creates a better visualization:

  • plt.plot(): Creates the connecting lines between points
  • plt.scatter(): Creates the individual data points
  • Together they show both the trend and the individual data points

For line plots showing frequency, you might use just plt.scatter() to show individual occurrences, or combine both to show the relationship between values.

You can also use just one depending on your needs, but combining both gives the clearest visualization.

Question: What's the difference between Counter and regular counting in Python?

Answer: Here's the difference:

  • Regular counting: Using loops to manually count occurrences
  • Counter: A specialized tool that automatically counts occurrences

Example with regular counting:

counts = {}
for item in data:
    if item in counts:
        counts[item] += 1
    else:
        counts[item] = 1

Example with Counter:

from collections import Counter
counts = Counter(data)

Counter is much more efficient and less error-prone!

Question: Can I use other libraries besides matplotlib for line plots in Python?

Answer: Yes, there are several alternatives:

  • Seaborn: Higher-level interface built on matplotlib
  • Plotly: Interactive plots and charts
  • Bokeh: Interactive visualization for large datasets
  • Altair: Grammar of graphics approach

However, matplotlib is the most fundamental and widely used, making it the best starting point for learning data visualization in Python.

For basic line plots, matplotlib is usually the simplest choice.