Bird
Raised Fist0
Matplotlibdata~20 mins

Diverging bar charts in Matplotlib - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Diverging Bar Chart Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of a simple diverging bar chart code

What will be the output of this Python code using matplotlib to create a diverging bar chart?

Matplotlib
import matplotlib.pyplot as plt
import numpy as np

labels = ['A', 'B', 'C', 'D']
values = np.array([3, -2, 5, -1])
colors = ['green' if x > 0 else 'red' for x in values]

plt.bar(labels, values, color=colors)
plt.axhline(0, color='black')
plt.show()
AA line chart connecting points A, B, C, D with values 3, -2, 5, -1.
BA bar chart with all bars in blue, some going up and some going down, with no horizontal line.
CA scatter plot with points at (A,3), (B,-2), (C,5), (D,-1) colored green and red.
DA bar chart with bars for A and C going up in green, bars for B and D going down in red, and a black horizontal line at zero.
Attempts:
2 left
💡 Hint

Look at how colors are assigned based on positive or negative values and the use of axhline.

❓ data_output
intermediate
1:30remaining
Number of bars above and below zero

Given the following data and code for a diverging bar chart, how many bars will be above zero and how many below zero?

Matplotlib
import numpy as np
values = np.array([10, -5, 0, 3, -7, 2])
AAbove zero: 3 bars; Below zero: 2 bars
BAbove zero: 4 bars; Below zero: 2 bars
CAbove zero: 3 bars; Below zero: 3 bars
DAbove zero: 2 bars; Below zero: 3 bars
Attempts:
2 left
💡 Hint

Count values strictly greater than zero and strictly less than zero. Zero is neither.

❓ visualization
advanced
2:00remaining
Identify the correct diverging bar chart visualization

Which of the following code snippets produces a diverging bar chart with labels on the y-axis and horizontal bars diverging from zero?

Aplt.scatter(labels, values, color='red')
Bplt.barh(labels, values, color=['red' if v < 0 else 'blue' for v in values]); plt.axvline(0, color='black')
Cplt.plot(labels, values, color='blue')
Dplt.bar(labels, values, color=['red' if v < 0 else 'blue' for v in values]); plt.axhline(0, color='black')
Attempts:
2 left
💡 Hint

Think about which function creates horizontal bars and where the zero line should be.

🔧 Debug
advanced
1:30remaining
Identify the error in diverging bar chart code

What error will this code raise?

import matplotlib.pyplot as plt
values = [4, -3, 2, -1]
colors = ['green' if x > 0 else 'red' for x in values]
plt.bar(range(len(values)), values, color=colors)
plt.axhline(0, color='black')
plt.show()
ANo error; the code runs and shows a diverging bar chart.
BTypeError because colors list length does not match bars.
CValueError because plt.bar expects labels, not range indices.
DNameError because 'plt' is not imported.
Attempts:
2 left
💡 Hint

Check if the colors list length matches the number of bars and if imports are correct.

🚀 Application
expert
2:30remaining
Calculate net positive and negative sums from diverging bar chart data

Given the following data representing changes in sales (positive and negative), what are the total positive and total negative sums?

sales_changes = [15, -7, 0, 8, -3, -5, 12]
ATotal positive sum: 27; Total negative sum: -15
BTotal positive sum: 35; Total negative sum: -10
CTotal positive sum: 35; Total negative sum: -15
DTotal positive sum: 27; Total negative sum: -10
Attempts:
2 left
💡 Hint

Add only positive numbers for positive sum, and only negative numbers for negative sum.

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