compare two items on a bar graph in python

To compare two items on a bar graph in Python using Matplotlib library, follow these steps:

  1. Import the necessary libraries and dependencies:
main.py
import matplotlib.pyplot as plt
import numpy as np
51 chars
3 lines
  1. Define the data points for the bar chart:
main.py
items = ["Item A", "Item B", "Item C", "Item D", "Item E"]
quantity1 = [100, 200, 300, 400, 500]
quantity2 = [200, 300, 400, 500, 600]
135 chars
4 lines
  1. Create the bar chart and customize it using Matplotlib:
main.py
# set the width of the bars
barWidth = 0.25

# set the position of the bars on the x-axis
r1 = np.arange(len(quantity1))
r2 = [x + barWidth for x in r1]

# plot the bars
plt.bar(r1, quantity1, color='blue', width=barWidth, edgecolor='white', label='Item 1')
plt.bar(r2, quantity2, color='green', width=barWidth, edgecolor='white', label='Item 2')

# add xticks on the middle of the group bars
plt.xlabel('Items', fontweight='bold')
plt.xticks([r + barWidth for r in range(len(quantity1))], items)

# add a legend
plt.legend()

# show the graph
plt.show()
555 chars
21 lines

This will create a bar chart with two bars for each item displaying the quantities for each item in a different color. You can adjust the colors, label names, and other customization options as needed.

gistlibby LogSnag