Bird
Raised Fist0
Matplotlibdata~10 mins

Basic histogram with plt.hist in Matplotlib - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Basic histogram with plt.hist
Start with data array
↓
Call plt.hist(data)
↓
Calculate bins and counts
↓
Draw bars for each bin
↓
Show histogram plot
↓
End
The flow starts with data, then plt.hist calculates bins and counts, draws bars, and finally shows the histogram.
Execution Sample
Matplotlib
import matplotlib.pyplot as plt

data = [1,2,2,3,3,3,4,4,4,4]
plt.hist(data, bins=4)
plt.show()
This code creates a histogram of the data list with 4 bins and displays the plot.
Execution Table
StepActionData StateBinsBin CountsPlot Action
1Start with data[1,2,2,3,3,3,4,4,4,4]N/AN/ANo plot yet
2Call plt.hist(data, bins=4)[1,2,2,3,3,3,4,4,4,4][1.0-1.75,1.75-2.5,2.5-3.25,3.25-4.0]Counts calculatedBars prepared
3Count data in binsSame dataSame bins[1,2,3,4]Bars heights set
4Draw histogram barsSame dataSame binsSame countsBars drawn on plot
5Show plotSame dataSame binsSame countsHistogram displayed
6EndSame dataSame binsSame countsPlot window open
💡 Plot is shown and program waits for user to close window
Variable Tracker
VariableStartAfter plt.hist callAfter counts calculationAfter plot drawFinal
data[1,2,2,3,3,3,4,4,4,4]SameSameSameSame
binsN/A[1.0-1.75,1.75-2.5,2.5-3.25,3.25-4.0]SameSameSame
countsN/AN/A[1,2,3,4]SameSame
Key Moments - 3 Insights
Why do the bin ranges not exactly match the data values?
Bins are calculated to cover the data range evenly; for example, with 4 bins from 1 to 4, each bin covers a range like 1.0-1.75. This is shown in execution_table step 2.
Why does the count for the last bin include 4 values?
Because the last bin includes the upper edge, so all data points equal to 4 fall into the last bin, as seen in execution_table step 3.
What happens if plt.show() is not called?
The histogram bars are prepared but the plot window does not appear, so the user cannot see the histogram. This is implied between steps 4 and 5.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table at step 3, what is the count of data points in the second bin?
A1
B3
C2
D4
💡 Hint
Check the 'Bin Counts' column at step 3 in the execution_table.
At which step does the histogram bars get drawn on the plot?
AStep 3
BStep 4
CStep 2
DStep 5
💡 Hint
Look at the 'Plot Action' column in the execution_table.
If the number of bins is increased to 5, what will happen to the counts in the bins?
ACounts will be distributed into 5 smaller bins
BCounts will remain the same as 4 bins
CCounts will double
DCounts will be zero
💡 Hint
Refer to how bins split data in the execution_table and variable_tracker.
Concept Snapshot
plt.hist(data, bins=n) creates a histogram.
Data is split into n bins covering the data range.
Counts of data points per bin are calculated.
Bars are drawn with heights = counts.
plt.show() displays the histogram plot.
Full Transcript
This visual execution traces how matplotlib's plt.hist function creates a histogram. Starting with a data list, plt.hist divides the data range into bins, counts how many data points fall into each bin, draws bars representing these counts, and finally shows the plot window. The execution table shows each step: starting with data, calling plt.hist, calculating bins and counts, drawing bars, and displaying the plot. Variables like data, bins, and counts are tracked to see their values change or stay the same. Key moments clarify why bins cover ranges and how counts are assigned. The quiz tests understanding of bin counts, drawing steps, and effects of changing bin numbers. The snapshot summarizes the main steps and syntax for quick reference.

Practice

(1/5)
1. What does the plt.hist() function do in matplotlib?
easy
A. It creates a scatter plot of two variables.
B. It plots a line graph connecting data points.
C. It creates a histogram to show data frequency distribution.
D. It generates a pie chart to show proportions.

Solution

  1. Step 1: Understand the purpose of plt.hist()

    The function plt.hist() groups data into bins and shows how often values fall into each bin.
  2. Step 2: Compare with other plot types

    Line graphs connect points, scatter plots show points, and pie charts show parts of a whole, which are different from histograms.
  3. Final Answer:

    It creates a histogram to show data frequency distribution. -> Option C
  4. Quick Check:

    Histogram = frequency bars [OK]
Hint: Histograms show frequency counts in bars [OK]
Common Mistakes:
  • Confusing histogram with line plot
  • Thinking plt.hist() creates scatter plots
  • Mixing histogram with pie chart
2. Which of the following is the correct way to create a histogram of data stored in a list named data using matplotlib?
easy
A. plt.histogram(data); plt.show()
B. plt.plot.hist(data); plt.show()
C. plt.bar(data); plt.show()
D. plt.hist(data); plt.show()

Solution

  1. Step 1: Recall the correct function name

    The correct function to create a histogram is plt.hist(), not plt.plot.hist() or plt.histogram().
  2. Step 2: Confirm usage with plt.show()

    After plotting, plt.show() displays the figure. Using plt.bar() creates bar charts, not histograms.
  3. Final Answer:

    plt.hist(data); plt.show() -> Option D
  4. Quick Check:

    Use plt.hist() for histograms [OK]
Hint: Use plt.hist() to plot histograms, then plt.show() [OK]
Common Mistakes:
  • Using plt.plot.hist() which is invalid
  • Calling plt.histogram() which doesn't exist
  • Using plt.bar() instead of plt.hist()
3. What will be the output of the following code?
import matplotlib.pyplot as plt

values = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
plt.hist(values, bins=4)
plt.show()
medium
A. A histogram with 4 bars showing frequencies: 1, 2, 3, and 4
B. A histogram with 10 bars, one for each value
C. A line plot connecting the values 1 to 4
D. An error because bins must be greater than 4

Solution

  1. Step 1: Understand bins parameter

    Setting bins=4 divides the data range into 4 intervals (bins).
  2. Step 2: Count frequencies in each bin

    The values 1, 2, 3, and 4 fall into these bins with frequencies 1, 2, 3, and 4 respectively, so the histogram shows 4 bars with these heights.
  3. Final Answer:

    A histogram with 4 bars showing frequencies: 1, 2, 3, and 4 -> Option A
  4. Quick Check:

    Bins split data; bars show counts [OK]
Hint: Bins split data; bar height = count in bin [OK]
Common Mistakes:
  • Thinking bins=4 means 10 bars
  • Confusing histogram with line plot
  • Assuming bins must be greater than data length
4. Identify the error in this code snippet that tries to plot a histogram:
import matplotlib.pyplot as plt

values = [5, 7, 8, 5, 6]
plt.hist(values, bins='five')
plt.show()
medium
A. plt.show() is missing and needed to display the plot.
B. The bins parameter should be an integer, not a string.
C. plt.hist() requires a color argument.
D. The values list contains invalid data types.

Solution

  1. Step 1: Check bins parameter type

    The bins argument must be an integer or sequence of numbers, not a string like 'five'.
  2. Step 2: Verify other parts

    The data list is valid, color is optional, and plt.show() is present, so no other errors.
  3. Final Answer:

    The bins parameter should be an integer, not a string. -> Option B
  4. Quick Check:

    Bins must be int or list, not string [OK]
Hint: Bins must be number, not text [OK]
Common Mistakes:
  • Passing bins as a string instead of integer
  • Thinking color is required
  • Forgetting plt.show() (not the case here)
5. You have a dataset of exam scores ranging from 0 to 100. You want to create a histogram with 5 equal-width bins and color the bars blue. Which code snippet correctly achieves this?
hard
A. plt.hist(scores, bins=5, color='blue'); plt.show()
B. plt.hist(scores, bins=[0,20,50,70,90,100], color='blue'); plt.show()
C. plt.hist(scores, bins=5, colors='blue'); plt.show()
D. plt.hist(scores, bins=5, color=blue); plt.show()

Solution

  1. Step 1: Use bins=integer for equal-width

    bins=5 automatically divides the range (0-100) into 5 equal-width bins of 20 units each: [0-20, 20-40, 40-60, 60-80, 80-100].
  2. Step 2: Color the bars blue

    The color='blue' parameter sets the bar color correctly.
  3. Step 3: Eliminate distractors

    B specifies explicit bins [0,20,50,70,90,100] with unequal widths (20,30,20,20,10); C uses invalid 'colors'; D has unquoted 'blue' causing NameError.
  4. Final Answer:

    plt.hist(scores, bins=5, color='blue'); plt.show() -> Option A
  5. Quick Check:

    bins=5 (equal width) + color='blue' [OK]
Hint: bins=5 for equal-width over data range, color='blue' [OK]
Common Mistakes:
  • Using explicit bins with unequal widths
  • Using 'colors' instead of 'color'
  • Using color=blue without quotes
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard