Learn

Ah, the pie chart. It’s a bit divisive in data visualization. Supporters say it’s an intuitive way to visualize the breakdown of a whole into parts, and detractors say that it’s clunky and likely to mislead people.

Here at Codecademy, we just follow some best practices: pie charts work best for breakdowns of 2-8 parts, and they are only a good choice when the takeaway doesn’t have to be too granular. People can’t tell the difference between 18% and 20% when looking at a pie chart, but they can compare “about 30%” to “about 50%”, for example.

With those strengths and limitations in mind, how do we make a pie chart using matplotlib? We use the plt.pie() function! plt.pie() takes the following parameters:

  • x: the numeric variable shown as pieces of the pie. The function adds up all the x values to compare part and whole and auto-generate the pieces of the pie.
  • labels: the variable used to label each section of the pie chart
  • startangle: the rotation of the pie chart, adjusted to improve readability
  • colors: an array of colors the chart will cycle through. If blank, defaults to matplotlib’s default 10-color “Tableau” palette.

x is the only required parameter here, but the others can all help make the pie chart more readable. A pie chart showing the five favorite donut flavors of conference attendees might be written with the following code:

plt.pie(x = data.donut_vote_count, labels = data.donut_flavor, startangle = 30, colors = ['brown', 'pink', 'purple', 'white', 'red'])

The startangle may or may not need adjusting – generally, this depends on how the pie pieces (and subsequently their labels) are distributed.

Instructions

1.

Run the Setup cells to load in the necessary packages and the EV_market_share_3 csv. Run the cell below to view the columns in the pie_data dataset.

2.

Write the code to make a pie chart of the ‘number_sold’ column.

3.

Add labels to the pie chart using the 'model' column of the dataset.

4.

Set the start angle equal to 60.

5.

Optionally, change the colors in the chart. What happens if you only add one color? Or two? A complete list of named matplotlib colors can be found here.

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?