Diverging bar charts help us compare positive and negative values side by side. They make it easy to see which items are above or below a baseline.
0
0
Diverging bar charts in Matplotlib
Introduction
Comparing survey results with positive and negative responses.
Showing profit and loss for different products.
Visualizing changes that go up or down from zero.
Highlighting differences in ratings above or below average.
Syntax
Matplotlib
import matplotlib.pyplot as plt # Data labels = ['A', 'B', 'C', 'D'] values = [10, -5, 15, -10] # Plot plt.bar(labels, values, color=['green' if v >= 0 else 'red' for v in values]) plt.axhline(0, color='black') plt.show()
Use colors to separate positive and negative bars for clarity.
Draw a horizontal line at zero to show the baseline.
Examples
Simple diverging bar chart with custom colors for positive and negative values.
Matplotlib
import matplotlib.pyplot as plt labels = ['Jan', 'Feb', 'Mar'] values = [20, -10, 15] colors = ['blue' if v >= 0 else 'orange' for v in values] plt.bar(labels, values, color=colors) plt.axhline(0, color='gray') plt.show()
Adding a title to the diverging bar chart for better understanding.
Matplotlib
import matplotlib.pyplot as plt labels = ['X', 'Y', 'Z'] values = [-5, 10, -3] plt.bar(labels, values, color=['red' if v < 0 else 'green' for v in values]) plt.axhline(0, color='black') plt.title('Diverging Bar Chart') plt.show()
Sample Program
This program creates a diverging bar chart showing positive and negative values for products. Green bars go up, red bars go down, and a black line marks zero.
Matplotlib
import matplotlib.pyplot as plt # Categories and their values categories = ['Product A', 'Product B', 'Product C', 'Product D'] values = [30, -20, 15, -10] # Choose colors: green for positive, red for negative colors = ['green' if v >= 0 else 'red' for v in values] # Create bar chart plt.bar(categories, values, color=colors) # Draw baseline at zero plt.axhline(0, color='black') # Add labels and title plt.ylabel('Value') plt.title('Diverging Bar Chart Example') # Show plot plt.show()
OutputSuccess
Important Notes
Always include a zero baseline line to separate positive and negative bars clearly.
Use contrasting colors for positive and negative bars to make the chart easy to read.
Keep labels short and clear to avoid clutter.
Summary
Diverging bar charts show positive and negative values side by side.
Use colors and a zero line to make differences clear.
They are great for comparing gains and losses or opinions above and below a midpoint.