Bird
Raised Fist0
Matplotlibdata~10 mins

Diverging bar charts in Matplotlib - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Diverging bar charts
Prepare data with positive and negative values
↓
Sort or order data if needed
↓
Assign colors based on value sign
↓
Plot horizontal bars with lengths = values
↓
Add labels and title
↓
Display chart with diverging bars
This flow shows how to create a diverging bar chart by preparing data, assigning colors based on positive or negative values, plotting bars, and displaying the chart.
Execution Sample
Matplotlib
import matplotlib.pyplot as plt
values = [20, -15, 30, -10, 5]
colors = ['green' if v >= 0 else 'red' for v in values]
plt.barh(range(len(values)), values, color=colors)
plt.show()
This code plots a horizontal bar chart with bars colored green for positive and red for negative values.
Execution Table
StepActionVariable/ValueResult/Effect
1Define values listvalues = [20, -15, 30, -10, 5]List with positive and negative numbers created
2Assign colors based on signcolors = ['green' if v >= 0 else 'red' for v in values]colors = ['green', 'red', 'green', 'red', 'green']
3Call plt.barh with values and colorsplt.barh(range(5), values, color=colors)Horizontal bars plotted with correct colors
4Call plt.show()plt.show()Chart window opens showing diverging bar chart
5End-Execution stops after displaying chart
💡 Chart displayed and script ends
Variable Tracker
VariableStartAfter Step 1After Step 2Final
valuesundefined[20, -15, 30, -10, 5][20, -15, 30, -10, 5][20, -15, 30, -10, 5]
colorsundefinedundefined['green', 'red', 'green', 'red', 'green']['green', 'red', 'green', 'red', 'green']
Key Moments - 2 Insights
Why do some bars appear in red and others in green?
Bars are colored based on whether their values are negative or positive, as shown in step 2 of the execution table where colors are assigned conditionally.
What does plt.barh(range(len(values)), values, color=colors) do exactly?
It plots horizontal bars at positions 0 to 4 with lengths from values and colors from the colors list, as explained in step 3 of the execution table.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the color assigned to the value -10 at step 2?
Ablue
Bgreen
Cred
Dyellow
💡 Hint
Check the colors list in step 2 of the execution table where negative values get 'red'.
At which step does the chart actually get displayed?
AStep 1
BStep 4
CStep 3
DStep 5
💡 Hint
Look at the action in step 4 where plt.show() is called.
If the values list was all positive, how would the colors list change at step 2?
AAll colors would be 'green'
BAll colors would be 'red'
CColors would alternate between 'green' and 'red'
DColors would be empty
💡 Hint
Refer to the color assignment rule in step 2: positive values get 'green'.
Concept Snapshot
Diverging bar charts show positive and negative values with bars going right or left.
Use plt.barh() for horizontal bars.
Assign colors based on sign: green for positive, red for negative.
Plot bars with lengths = values and colors assigned.
Add labels and show chart with plt.show().
Full Transcript
This visual execution traces how to create a diverging bar chart using matplotlib in Python. First, a list of values with positive and negative numbers is defined. Then, colors are assigned to each value: green if the value is positive or zero, red if negative. Next, plt.barh() plots horizontal bars at positions 0 to 4 with lengths equal to the values and colors assigned accordingly. Finally, plt.show() displays the chart window with the diverging bars. The execution table shows each step and variable changes, helping beginners understand how the chart is built step-by-step.

Practice

(1/5)
1. What is the main purpose of a diverging bar chart in data visualization?
easy
A. To visualize hierarchical data using nested bars
B. To show positive and negative values side by side for easy comparison
C. To plot time series data with a line connecting points
D. To display only positive values in a stacked format

Solution

  1. Step 1: Understand the chart type

    Diverging bar charts are designed to display data that has both positive and negative values.
  2. Step 2: Identify the purpose

    They place positive and negative bars side by side to highlight differences clearly.
  3. Final Answer:

    To show positive and negative values side by side for easy comparison -> Option B
  4. Quick Check:

    Diverging bar chart = positive & negative side by side [OK]
Hint: Look for charts showing positive and negative bars side by side [OK]
Common Mistakes:
  • Confusing diverging bar charts with stacked bar charts
  • Thinking they only show positive values
  • Mixing up with line charts
2. Which of the following is the correct way to create a diverging bar chart using matplotlib's barh function for negative and positive values?
easy
A. plt.barh(y_pos, abs(values), color='red')
B. plt.barh(y_pos, values, color='blue')
C. plt.barh(y_pos, values, color=['red' if v < 0 else 'green' for v in values])
D. plt.barh(y_pos, values, color=['green' if v > 0 else 'blue' for v in values])

Solution

  1. Step 1: Understand color assignment for diverging bars

    Colors should differ based on whether values are positive or negative to highlight divergence.
  2. Step 2: Check the color list comprehension

    plt.barh(y_pos, values, color=['red' if v < 0 else 'green' for v in values]) uses a list comprehension assigning 'red' for negative and 'green' for positive values, which is correct.
  3. Final Answer:

    plt.barh(y_pos, values, color=['red' if v < 0 else 'green' for v in values]) -> Option C
  4. Quick Check:

    Color by sign = plt.barh(y_pos, values, color=['red' if v < 0 else 'green' for v in values]) [OK]
Hint: Use list comprehension to color bars by sign [OK]
Common Mistakes:
  • Using a single color for all bars
  • Taking absolute values which lose sign info
  • Assigning wrong colors to positive/negative values
3. Given the code below, what will be the color of the bar corresponding to the value -3?
import matplotlib.pyplot as plt
values = [4, -3, 2, -1]
y_pos = range(len(values))
colors = ['green' if v > 0 else 'red' for v in values]
plt.barh(y_pos, values, color=colors)
plt.show()
medium
A. No color (default)
B. Green
C. Blue
D. Red

Solution

  1. Step 1: Analyze the color assignment logic

    The list comprehension assigns 'green' if value > 0, else 'red'.
  2. Step 2: Check the value -3

    -3 is less than 0, so it gets 'red'.
  3. Final Answer:

    Red -> Option D
  4. Quick Check:

    Negative value color = red [OK]
Hint: Negative values get 'red' color here [OK]
Common Mistakes:
  • Assuming negative values get green
  • Confusing color assignment logic
  • Ignoring the else condition in list comprehension
4. The following code is intended to create a diverging bar chart but does not color bars correctly. What is the error?
values = [5, -2, 3, -4]
y_pos = range(len(values))
colors = ['green' if v < 0 else 'red' for v in values]
plt.barh(y_pos, values, color=colors)
plt.show()
medium
A. The color condition is reversed; positive values should be green
B. The y_pos variable should be a list, not a range
C. The barh function cannot accept a color list
D. Values should be absolute for coloring

Solution

  1. Step 1: Review the color condition

    The code assigns 'green' if value < 0, else 'red'. This means negative values are green and positive are red.
  2. Step 2: Understand diverging bar chart color convention

    Usually, positive values are green and negative values are red to show gains and losses clearly.
  3. Final Answer:

    The color condition is reversed; positive values should be green -> Option A
  4. Quick Check:

    Positive = green, negative = red [OK]
Hint: Positive bars usually green, negative bars red [OK]
Common Mistakes:
  • Reversing color conditions
  • Thinking range is invalid for y_pos
  • Using absolute values for coloring
5. You have a dataset with sales gains and losses for 5 products: {'A': 10, 'B': -5, 'C': 0, 'D': 7, 'E': -3}. How would you create a diverging bar chart that clearly shows gains in green, losses in red, and zero values in gray using matplotlib?
hard
A. Use a color list with a condition: green if >0, red if <0, gray if 0, then plot with plt.barh
B. Plot absolute values only with a single color to avoid confusion
C. Use plt.barh with colors assigned randomly
D. Plot only positive values and ignore zeros and negatives

Solution

  1. Step 1: Define color conditions for all cases

    Assign 'green' for positive, 'red' for negative, and 'gray' for zero values to distinguish all clearly.
  2. Step 2: Create color list and plot

    Use a list comprehension to assign colors based on value sign, then plot with plt.barh using these colors.
  3. Final Answer:

    Use a color list with a condition: green if >0, red if <0, gray if 0, then plot with plt.barh -> Option A
  4. Quick Check:

    Color by sign including zero = Use a color list with a condition: green if >0, red if <0, gray if 0, then plot with plt.barh [OK]
Hint: Add gray for zero values in color list [OK]
Common Mistakes:
  • Ignoring zero values color
  • Using absolute values losing sign info
  • Assigning random colors without logic
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