+91 81900 98289

Matplotlib Pie Charts

This Matplotlib Pie Charts lesson is for a beginner. Read the short notes, run each example, then change one name or number and run it again.

A pie chart shows parts of a whole. The values should be counts or shares of one total, and the slices should be few.

Five or more thin slices are hard to compare. A bar chart is clearer then.

Example 1: Start here

The shares here add up to 100. plt.pie(shares, labels=labels) draws them.

labels = ["Python", "SQL", "Other"] # a list; the values stay in this order shares = [50, 30, 20] # a list; the values stay in this order print(sum(shares)) # add the numbers together print(list(zip(labels, shares))) # zip keeps each pair together

Example 2: List the points

Matplotlib Pie Charts draws points. Printing each pair lets you check the data before a chart library plots it.

points = [(1, 13), (2, 12), (3, 18)] # a list; the values stay in this order for x, y in points: # repeat the indented lines once per value print(x, y) # a comma prints each value, with a space between

Example 3: Find the highest bar

The tallest bar is the largest number. max does that lookup.

heights = [13, 12, 18] # a list; the values stay in this order print(max(heights)) # the largest value

Example 4: Label each point

A chart label belongs with its number. zip keeps each day next to its height.

labels = ["Mon", "Tue", "Wed"] # a list; the values stay in this order heights = [13, 12, 18] # a list; the values stay in this order for label, height in zip(labels, heights): # repeat the indented lines once per value print(label, height) # a comma prints each value, with a space between
The shares here add up to 100. plt.pie(shares, labels=labels) draws them.
Call Now 81900 98289