How To Change Color Of Pie Chart In Python

In this tutorial, we will learn how to change the color of a pie chart in Python using the popular data visualization library matplotlib. A pie chart represents data in the form of slices, where each slice represents a percentage of the whole, allowing for an easy comparison of parts to the whole.

Step 1: Install the Required Libraries

First of all, we need to install the required library, matplotlib using the following command:

This command will install the matplotlib library in your Python environment if it is not already installed.

Step 2: Import the Required Libraries

Once the libraries are installed, we need to import them in the Python script. We will import the pyplot module from the matplotlib library.

Step 3: Prepare the Data

Now, let’s create some data to be represented in the pie chart. For this tutorial, we will use a simple example of the market share of different mobile operating systems. We will create two lists, one containing the names of the operating systems, and another containing their respective market shares.

Step 4: Create a Pie Chart With Custom Colors

We will now create a pie chart with custom colors for each slice using the pie() function from the matplotlib.pyplot module. We will pass the colors parameter which is a list of colors that will be used in the pie chart for the corresponding data slices.

The above code will create a pie chart with the provided data, labels, and colors. It will also display the percentage value of each slice on the chart using the autopct parameter.


Full Code


In this tutorial, we have learned how to change the color of a pie chart in Python using the matplotlib library. We created a simple pie chart representing the market share of different mobile operating systems and assigned custom colors to each of the slices. This skill can be used to further enhance and customize your data visualizations in Python.