Line Plot: A graph that shows frequency of data along a number line using X marks or dots.
- Import matplotlib.pyplot
- Prepare your data as a list
- Use plt.plot() to create the line plot
- Add labels and title
- Display the plot with plt.show()
import matplotlib.pyplot as plt
import numpy as np
heights = [54, 56, 54, 57, 55, 54, 56, 55, 57, 54]
# 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 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.
import matplotlib.pyplot as plt
from collections import Counter
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]
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()
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.
import matplotlib.pyplot as plt
import numpy as np
plant_heights = [8, 7, 8, 9, 7, 8, 7, 9, 8, 7]
# 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()
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.
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.
• 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
- Import libraries: import matplotlib.pyplot as plt
- Prepare data: Create lists or arrays with your data
- Process data: Count frequencies if needed
- Create plot: Use plt.plot() and plt.scatter()
- Add details: Labels, title, grid
- Show plot: Use plt.show()
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()
• 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
• 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
• 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
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.
import matplotlib.pyplot as plt
from collections import Counter
backpack_weights = [12, 15, 12, 16, 14, 12, 15, 14, 16, 12]
# 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")
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.
import matplotlib.pyplot as plt
from collections import Counter
reading_minutes = [30, 35, 30, 40, 35, 30, 45, 35, 40, 30, 35, 40]
# 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})")
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
Matplotlib: The foundational plotting library for Python.
Pandas: For data manipulation and analysis.
NumPy: For numerical computations.
Seaborn: For statistical data visualization.
- Import 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: Show the final plot
• 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.