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:
1 |
!pip install matplotlib |
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.
1 |
import matplotlib.pyplot as plt |
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.
1 2 |
operating_systems = ['Android', 'iOS', 'Windows', 'Others'] market_share = [74.6, 22.9, 1.3, 1.2] |
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.
1 2 3 4 5 6 |
colors = ['lime', 'orange', 'blue', 'lightblue'] plt.pie(market_share, labels=operating_systems, colors=colors, autopct='%.1f%%') plt.title('Market Share of Mobile Operating Systems') plt.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle. plt.show() |
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.
Output

Full Code
1 2 3 4 5 6 7 8 9 10 11 |
import matplotlib.pyplot as plt operating_systems = ['Android', 'iOS', 'Windows', 'Others'] market_share = [74.6, 22.9, 1.3, 1.2] colors = ['lime', 'orange', 'blue', 'lightblue'] plt.pie(market_share, labels=operating_systems, colors=colors, autopct='%.1f%%') plt.title('Market Share of Mobile Operating Systems') plt.axis('equal') plt.show() |
Conclusion
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.