1 Hour

3. Plotting Categorical Data

Introduction to Bar Charts

Bar charts are essential for visualizing categorical data. In matplotlib, we use plt.bar for vertical bars and plt.barh for horizontal bars. These functions require two primary inputs: the categories for the x or y axis, and the numerical values for the height or width of the bars.

You can customize the appearance of your bars using parameters like color, width, and align. Always ensure you set your ticks correctly using plt.xticks or plt.yticks to label your categories clearly.

Operator Note: For large datasets with many categories, plt.barh is generally easier to read as labels do not overlap.
Python 3
import matplotlib.pyplot as plt
categories = ['A', 'B', 'C']
values = [10, 20, 15]
plt.bar(categories, values, color='skyblue')
plt.title('Vertical Bar Chart')
plt.show()

Pie Charts and Proportions

A plt.pie chart represents data as slices of a whole. While intuitive for showing parts of a total, use them sparingly. They are best when you have few categories. Crucial parameters include labels, autopct for percentage formatting, and startangle for rotating the chart.

Consider using plt.bar as an alternative if you need to compare relative sizes precisely, as the human eye is better at comparing lengths than angular areas.

Operator Note: Avoid pie charts if you have more than 5 categories to maintain readability.
Python 3
import matplotlib.pyplot as plt
labels = ['Segment 1', 'Segment 2', 'Segment 3']
sizes = [30, 45, 25]
plt.pie(sizes, labels=labels, autopct='%1.1f%%')
plt.show()

Knowledge Check

Ready to test your understanding of 3. Plotting Categorical Data?

Back