Bird
Raised Fist0
Matplotlibdata~10 mins

Horizontal bar chart with plt.barh in Matplotlib - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Horizontal bar chart with plt.barh
Prepare data: categories, values
↓
Call plt.barh(categories, values)
↓
Matplotlib draws horizontal bars
↓
Show or save the plot
↓
END
We prepare categories and their values, then call plt.barh to draw horizontal bars, and finally display the chart.
Execution Sample
Matplotlib
import matplotlib.pyplot as plt
categories = ['A', 'B', 'C']
values = [5, 3, 7]
plt.barh(categories, values)
plt.show()
This code draws a horizontal bar chart with three categories and their values.
Execution Table
StepActionInputOutput/Effect
1Prepare categories list['A', 'B', 'C']List ready for plotting
2Prepare values list[5, 3, 7]Values ready for plotting
3Call plt.barh(categories, values)categories=['A','B','C'], values=[5,3,7]Horizontal bars drawn: A=5, B=3, C=7
4Call plt.show()NonePlot window opens showing horizontal bar chart
5User closes plot windowNoneExecution ends
💡 Plot displayed and program ends after user closes the window
Variable Tracker
VariableStartAfter Step 1After Step 2Final
categoriesNone['A', 'B', 'C']['A', 'B', 'C']['A', 'B', 'C']
valuesNoneNone[5, 3, 7][5, 3, 7]
Key Moments - 3 Insights
Why do we pass categories first and values second in plt.barh?
plt.barh expects the first argument as the y-axis labels (categories) and the second as the bar lengths (values). This matches the horizontal layout where categories go vertically.
What happens if categories and values lists have different lengths?
Matplotlib will raise an error because each category needs a corresponding value. See execution_table step 3 where inputs must match in length.
Why do we call plt.show() after plt.barh?
plt.barh prepares the plot but does not display it. plt.show() opens the window to display the chart, as shown in execution_table step 4.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 'values' after Step 2?
A['A', 'B', 'C']
B[5, 3, 7]
CNone
D[3, 5, 7]
💡 Hint
Check variable_tracker row for 'values' after Step 2
At which step does the horizontal bar chart actually get drawn?
AStep 3
BStep 1
CStep 4
DStep 5
💡 Hint
See execution_table action column for when plt.barh is called
If we swapped categories and values in plt.barh, what would happen?
AMatplotlib would raise an error immediately
BPlot would show correctly with no change
CBars would be drawn with categories as lengths and values as labels
DBars would be vertical instead of horizontal
💡 Hint
Recall plt.barh expects categories first, values second (see key_moments)
Concept Snapshot
plt.barh(categories, values) draws horizontal bars.
First argument: categories (y-axis labels).
Second argument: values (bar lengths).
Call plt.show() to display the plot.
Categories and values must be same length.
Useful for comparing quantities across categories horizontally.
Full Transcript
We start by preparing two lists: categories and values. Categories are labels like 'A', 'B', 'C'. Values are numbers like 5, 3, 7. Then we call plt.barh(categories, values) which draws horizontal bars for each category with length equal to its value. Finally, plt.show() displays the chart window. The variables categories and values hold the data throughout. It's important that categories come first and values second in plt.barh. If their lengths differ, matplotlib will raise an error. The plot only appears after plt.show() is called. This method is great for visualizing data horizontally, making category comparison easy.

Practice

(1/5)
1. What does the plt.barh() function in matplotlib do?
easy
A. Generates a scatter plot with dots
B. Creates a vertical bar chart with bars extending bottom to top
C. Creates a horizontal bar chart with bars extending left to right
D. Plots a line graph connecting data points

Solution

  1. Step 1: Understand the function purpose

    plt.barh() is designed to create horizontal bar charts, where bars extend from left to right.
  2. Step 2: Compare with other plot types

    Vertical bar charts use plt.bar(), line graphs use plt.plot(), and scatter plots use plt.scatter().
  3. Final Answer:

    Creates a horizontal bar chart with bars extending left to right -> Option C
  4. Quick Check:

    Horizontal bar chart = plt.barh() [OK]
Hint: Remember 'h' in barh means horizontal bars [OK]
Common Mistakes:
  • Confusing plt.barh() with plt.bar()
  • Thinking plt.barh() creates vertical bars
  • Mixing bar charts with line or scatter plots
2. Which of the following is the correct syntax to create a horizontal bar chart with categories ['A', 'B', 'C'] and values [5, 7, 3] using matplotlib?
easy
A. plt.barh(['A', 'B', 'C'], [5, 7, 3])
B. plt.bar([5, 7, 3], ['A', 'B', 'C'])
C. plt.barh([5, 7, 3], ['A', 'B', 'C'])
D. plt.plot(['A', 'B', 'C'], [5, 7, 3])

Solution

  1. Step 1: Identify correct function and argument order

    plt.barh() takes categories as the first argument (y-axis labels) and values as the second argument (bar lengths).
  2. Step 2: Check each option

    plt.barh(['A', 'B', 'C'], [5, 7, 3]) correctly uses plt.barh(['A', 'B', 'C'], [5, 7, 3]). plt.bar([5, 7, 3], ['A', 'B', 'C']) uses vertical bars and reverses arguments. plt.barh([5, 7, 3], ['A', 'B', 'C']) reverses arguments for horizontal bars. plt.plot(['A', 'B', 'C'], [5, 7, 3]) plots a line graph.
  3. Final Answer:

    plt.barh(['A', 'B', 'C'], [5, 7, 3]) -> Option A
  4. Quick Check:

    Categories first, values second in plt.barh() [OK]
Hint: In plt.barh(), categories come first, then values [OK]
Common Mistakes:
  • Swapping categories and values in arguments
  • Using plt.bar() instead of plt.barh() for horizontal bars
  • Using plt.plot() instead of bar chart functions
3. What will be the output of the following code?
import matplotlib.pyplot as plt
categories = ['X', 'Y', 'Z']
values = [10, 5, 8]
plt.barh(categories, values, color='green')
plt.show()
medium
A. A vertical bar chart with green bars for categories X, Y, Z
B. A line plot connecting points (X,10), (Y,5), (Z,8)
C. An error because color must be a list
D. A horizontal bar chart with green bars for categories X, Y, Z

Solution

  1. Step 1: Analyze the function and parameters

    The code uses plt.barh() with categories on y-axis and values as bar lengths, colored green.
  2. Step 2: Understand the plot output

    This produces a horizontal bar chart with green bars labeled X, Y, Z with lengths 10, 5, and 8 respectively.
  3. Final Answer:

    A horizontal bar chart with green bars for categories X, Y, Z -> Option D
  4. Quick Check:

    plt.barh() + color='green' = horizontal green bars [OK]
Hint: plt.barh() always creates horizontal bars, color accepts string [OK]
Common Mistakes:
  • Thinking plt.barh() creates vertical bars
  • Assuming color must be a list
  • Confusing bar chart with line plot
4. Identify the error in this code snippet that tries to create a horizontal bar chart:
import matplotlib.pyplot as plt
labels = ['A', 'B', 'C']
values = [4, 6, 8]
plt.barh(values, labels)
plt.show()
medium
A. plt.barh() does not accept lists as arguments
B. Arguments are reversed; categories should be first, values second
C. Missing plt.show() call
D. Color argument is required for plt.barh()

Solution

  1. Step 1: Check argument order in plt.barh()

    The first argument should be categories (labels), the second argument should be values (bar lengths).
  2. Step 2: Identify the mistake in the code

    The code passes values first and labels second, which reverses the expected order and causes incorrect plotting.
  3. Final Answer:

    Arguments are reversed; categories should be first, values second -> Option B
  4. Quick Check:

    plt.barh(categories, values) order matters [OK]
Hint: Categories first, values second in plt.barh() [OK]
Common Mistakes:
  • Swapping the order of categories and values
  • Forgetting plt.show() (though present here)
  • Thinking color argument is mandatory
5. You have a dataset with categories ['Jan', 'Feb', 'Mar'] and sales [200, 150, 300]. You want to create a horizontal bar chart with red bars, bar height of 0.5, and display the sales values on the bars. Which code snippet correctly achieves this?
hard
A. plt.barh(['Jan', 'Feb', 'Mar'], [200, 150, 300], color='red', height=0.5) for i, v in enumerate([200, 150, 300]): plt.text(v + 5, i, str(v)) plt.show()
B. plt.barh([200, 150, 300], ['Jan', 'Feb', 'Mar'], color='red', height=0.5) plt.show()
C. plt.bar(['Jan', 'Feb', 'Mar'], [200, 150, 300], color='red', height=0.5) plt.show()
D. plt.barh(['Jan', 'Feb', 'Mar'], [200, 150, 300], color='red', width=0.5) plt.show()

Solution

  1. Step 1: Use plt.barh() with correct arguments

    Categories come first, then values. Set color='red' and height=0.5 to adjust bar thickness.
  2. Step 2: Add sales values as text labels on bars

    Use a for loop with plt.text() to place sales numbers slightly right of each bar end.
  3. Step 3: Verify other options

    plt.barh([200, 150, 300], ['Jan', 'Feb', 'Mar'], color='red', height=0.5) plt.show() reverses arguments, plt.bar(['Jan', 'Feb', 'Mar'], [200, 150, 300], color='red', height=0.5) plt.show() uses vertical bars, plt.barh(['Jan', 'Feb', 'Mar'], [200, 150, 300], color='red', width=0.5) plt.show() uses 'width' instead of 'height' which is invalid for barh.
  4. Final Answer:

    plt.barh(['Jan', 'Feb', 'Mar'], [200, 150, 300], color='red', height=0.5) for i, v in enumerate([200, 150, 300]): plt.text(v + 5, i, str(v)) plt.show() -> Option A
  5. Quick Check:

    plt.barh(categories, values, height=0.5) + plt.text() labels [OK]
Hint: Use height for bar thickness in plt.barh(), add labels with plt.text() [OK]
Common Mistakes:
  • Swapping categories and values
  • Using width instead of height for bar thickness
  • Not adding text labels or placing them incorrectly
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