0
0
Matplotlibdata~5 mins

Before-after comparison plots in Matplotlib

Choose your learning style9 modes available
Introduction

Before-after comparison plots help us see changes clearly by showing data from two times side by side.

To compare test scores of students before and after a training program.
To check sales numbers before and after a marketing campaign.
To observe weight changes before and after a diet plan.
To analyze temperature differences before and after installing new equipment.
Syntax
Matplotlib
import matplotlib.pyplot as plt

# Data for before and after
before = [value1, value2, ...]
after = [value1, value2, ...]

# Create x positions
x = range(len(before))

# Plot lines connecting before and after
plt.plot(x, before, 'o-', label='Before')
plt.plot(x, after, 's-', label='After')

# Add labels and legend
plt.xlabel('Items')
plt.ylabel('Values')
plt.title('Before-After Comparison')
plt.legend()
plt.show()

Use markers like 'o' and 's' to show points clearly.

Connecting lines help visualize changes between before and after.

Examples
Simple plot with default x positions (0,1,2) showing before and after values.
Matplotlib
before = [5, 7, 9]
after = [6, 8, 10]

plt.plot(before, 'o-', label='Before')
plt.plot(after, 's-', label='After')
plt.legend()
plt.show()
Using custom x labels to represent categories.
Matplotlib
x = ['A', 'B', 'C']
before = [3, 4, 5]
after = [4, 5, 6]

plt.plot(x, before, 'o-', label='Before')
plt.plot(x, after, 's-', label='After')
plt.legend()
plt.show()
Adding dashed lines to connect before and after points for each item.
Matplotlib
before = [10, 15, 20]
after = [12, 18, 22]
x = range(len(before))

for i in x:
    plt.plot([i, i], [before[i], after[i]], 'k--')
plt.plot(x, before, 'o-', label='Before')
plt.plot(x, after, 's-', label='After')
plt.legend()
plt.show()
Sample Program

This code shows sales data before and after a campaign for 5 months. Dashed lines connect each month's before and after sales to highlight changes.

Matplotlib
import matplotlib.pyplot as plt

# Sample data: sales before and after a campaign
before = [100, 150, 200, 250, 300]
after = [120, 160, 210, 280, 330]

x = range(len(before))

# Plot lines connecting before and after values
for i in x:
    plt.plot([i, i], [before[i], after[i]], 'gray', linestyle='--')

plt.plot(x, before, 'o-', color='blue', label='Before')
plt.plot(x, after, 's-', color='green', label='After')

plt.xlabel('Month')
plt.ylabel('Sales')
plt.title('Sales Before and After Campaign')
plt.legend()
plt.show()
OutputSuccess
Important Notes

Make sure before and after lists have the same length.

Use clear labels and legends to help understand the plot.

Colors and markers make it easier to distinguish before and after data.

Summary

Before-after plots show changes clearly by plotting two sets of data points.

Connecting lines help visualize the difference for each item.

Use labels, legends, and colors to make the plot easy to read.