-->

Python - Matplotlib Pyplot Part 3: Bar Charts

Bar charts are used for categorical data representation.

Examples and Explanation

Basic Bar Chart

categories = ['A', 'B', 'C', 'D']

values = [4, 7, 1, 8]

plt.bar(categories, values)

plt.title("Basic Bar Chart")

plt.show()

Explanation: The bar() function is ideal for visualizing comparisons among categories.

Horizontal Bar Chart

plt.barh(categories, values)

plt.title("Horizontal Bar Chart")

plt.show()

Explanation: A horizontal bar chart can make categorical comparisons more intuitive.

Grouped Bar Chart

categories = ['A', 'B', 'C']

values1 = [4, 7, 1]

values2 = [2, 5, 9]

bar_width = 0.3

x = range(len(categories))

plt.bar(x, values1, width=bar_width, label='Group 1')

plt.bar([i + bar_width for i in x], values2, width=bar_width, label='Group 2')

plt.xticks([i + bar_width / 2 for i in x], categories)

plt.legend()

plt.title("Grouped Bar Chart")

plt.show()

Explanation: Grouped bar charts allow for direct comparison of multiple datasets.