How to Create A Pie Chart In Matplotlib?

11 minutes read

To create a pie chart in Matplotlib, you can follow these steps:

  1. Import the required libraries: import matplotlib.pyplot as plt
  2. Prepare your data: labels = ['Label1', 'Label2', 'Label3', ...] # Labels for each section of the pie sizes = [size1, size2, size3, ...] # Sizes/proportions for each section
  3. Create the pie chart: plt.pie(sizes, labels=labels) Optionally, you can use additional parameters such as colors, explode, startangle, etc. to customize the appearance of the chart.
  4. Add a title and/or legend (if desired): plt.title('Title of the Pie Chart') plt.legend()
  5. Display the chart: plt.show()
  6. If you want to save the chart as an image file instead of displaying it, you can use: plt.savefig('chart.png')


That's it! By following these steps, you can create a pie chart using Matplotlib in Python. Remember to adjust the data and customize the chart as per your requirements.

Best Matplotlib Books to Read in 2024

1
Data Visualization in Python with Pandas and Matplotlib

Rating is 5 out of 5

Data Visualization in Python with Pandas and Matplotlib

2
Matplotlib 3.0 Cookbook: Over 150 recipes to create highly detailed interactive visualizations using Python

Rating is 4.9 out of 5

Matplotlib 3.0 Cookbook: Over 150 recipes to create highly detailed interactive visualizations using Python

3
Matplotlib for Python Developers

Rating is 4.8 out of 5

Matplotlib for Python Developers

4
Numerical Python: Scientific Computing and Data Science Applications with Numpy, SciPy and Matplotlib

Rating is 4.7 out of 5

Numerical Python: Scientific Computing and Data Science Applications with Numpy, SciPy and Matplotlib

5
Matplotlib 2.x By Example: Multi-dimensional charts, graphs, and plots in Python

Rating is 4.6 out of 5

Matplotlib 2.x By Example: Multi-dimensional charts, graphs, and plots in Python

6
Matplotlib for Python Developers: Effective techniques for data visualization with Python, 2nd Edition

Rating is 4.5 out of 5

Matplotlib for Python Developers: Effective techniques for data visualization with Python, 2nd Edition

7
Python Data Analytics: With Pandas, NumPy, and Matplotlib

Rating is 4.4 out of 5

Python Data Analytics: With Pandas, NumPy, and Matplotlib

8
Python and Matplotlib Essentials for Scientists and Engineers (Iop Concise Physics)

Rating is 4.3 out of 5

Python and Matplotlib Essentials for Scientists and Engineers (Iop Concise Physics)

9
Hands-On Data Analysis with Pandas: A Python data science handbook for data collection, wrangling, analysis, and visualization, 2nd Edition

Rating is 4.2 out of 5

Hands-On Data Analysis with Pandas: A Python data science handbook for data collection, wrangling, analysis, and visualization, 2nd Edition

10
Data Visualization with Python for Beginners: Visualize Your Data using Pandas, Matplotlib and Seaborn (Machine Learning & Data Science for Beginners)

Rating is 4.1 out of 5

Data Visualization with Python for Beginners: Visualize Your Data using Pandas, Matplotlib and Seaborn (Machine Learning & Data Science for Beginners)


How to remove the top and right spines from a plot in Matplotlib?

To remove the top and right spines from a plot in Matplotlib, you can use the spines attribute of the Axes object and set their visibility to False. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
import matplotlib.pyplot as plt

# Create a figure and an axes object
fig, ax = plt.subplots()

# Generate some sample data
x = [0, 1, 2, 3, 4, 5]
y = [0, 1, 4, 9, 16, 25]

# Plot the data
ax.plot(x, y)

# Remove the top and right spines
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)

# Show the plot
plt.show()


In this example, we create a figure and an axes object using plt.subplots(). Then, we plot the data using ax.plot(x, y). Finally, we remove the top and right spines by setting their visibility to False using ax.spines['top'].set_visible(False) and ax.spines['right'].set_visible(False).


Running this code will display the plot with the top and right spines removed.


How to control axis tick labels in Matplotlib?

To control axis tick labels in Matplotlib, you can use the following methods:

  1. Customize the tick labels: plt.xticks() and plt.yticks() functions can be used to specify the positions and labels of the tick marks on the x-axis and y-axis, respectively. You can pass an array of values to these functions to set the positions of the tick marks. You can also pass a list of labels to set the corresponding tick labels.


Example 1: Changing x-axis tick labels to custom labels

1
2
3
4
5
6
7
8
9
import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]

plt.plot(x, y)
plt.xticks(x, ['A', 'B', 'C', 'D', 'E'])

plt.show()


Example 2: Setting x-axis tick labels to specific positions

1
2
3
4
5
6
7
8
9
import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]

plt.plot(x, y)
plt.xticks([1, 3, 5], ['Minimum', 'Average', 'Maximum'])

plt.show()


  1. Format the tick labels: You can use the plt.tick_params() function to customize various properties of the tick labels, such as font size, rotation, and alignment. You can set the labelsize parameter to specify the font size of the tick labels. You can set the rotation parameter to rotate the tick labels, and the ha (horizontal alignment) parameter to align them.


Example: Formatting x-axis tick labels

1
2
3
4
5
6
7
8
9
import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]

plt.plot(x, y)
plt.xticks(fontsize=12, rotation=45, ha='right')

plt.show()


These methods allow you to control the appearance of tick labels on the x-axis and y-axis in Matplotlib. You can adjust them according to your specific requirements.


How to create a stacked bar chart in Matplotlib?

To create a stacked bar chart in Matplotlib, you can follow these steps:

  1. Import the necessary libraries:
1
2
import matplotlib.pyplot as plt
import numpy as np


  1. Define the data for the chart. In this example, we will use three categories and their respective values:
1
2
3
categories = ['Category 1', 'Category 2', 'Category 3']
values1 = [10, 15, 12]
values2 = [8, 12, 10]


  1. Compute the cumulative values for each category. This is required to create the stacked bars:
1
2
bottom_values1 = np.zeros(len(values1))
bottom_values2 = values1


  1. Create the bar chart using the bar function. Pass the x-coordinate (position of the bars), values, and bottom values for each category:
1
2
plt.bar(categories, values1, label='Value 1')
plt.bar(categories, values2, bottom=bottom_values2, label='Value 2')


  1. Customize the chart by adding labels, legend, and title:
1
2
3
4
plt.xlabel('Categories')
plt.ylabel('Values')
plt.legend()
plt.title('Stacked Bar Chart')


  1. Finally, display the chart:
1
plt.show()


Here's the complete code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
import matplotlib.pyplot as plt
import numpy as np

categories = ['Category 1', 'Category 2', 'Category 3']
values1 = [10, 15, 12]
values2 = [8, 12, 10]

bottom_values1 = np.zeros(len(values1))
bottom_values2 = values1

plt.bar(categories, values1, label='Value 1')
plt.bar(categories, values2, bottom=bottom_values2, label='Value 2')

plt.xlabel('Categories')
plt.ylabel('Values')
plt.legend()
plt.title('Stacked Bar Chart')

plt.show()


This will create a stacked bar chart with two values for each category.


How to create a polar plot in Matplotlib?

To create a polar plot in Matplotlib, you can follow these steps:

  1. Import the necessary libraries:
1
2
import numpy as np
import matplotlib.pyplot as plt


  1. Define the data for the polar plot:
1
2
theta = np.linspace(0, 2*np.pi, 100)
radius = np.abs(np.sin(5*theta))


  1. Create a polar plot using the plt.polar function:
1
plt.polar(theta, radius)


  1. Customize the plot by adding labels, title, or grid lines:
1
2
3
4
plt.xlabel("Theta")
plt.ylabel("Radius")
plt.title("Polar Plot")
plt.grid(True)


  1. Show the polar plot using plt.show():
1
plt.show()


Here's an example of creating a simple polar plot with a sinusoidal curve:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import numpy as np
import matplotlib.pyplot as plt

theta = np.linspace(0, 2*np.pi, 100)
radius = np.abs(np.sin(5*theta))

plt.polar(theta, radius)
plt.xlabel("Theta")
plt.ylabel("Radius")
plt.title("Polar Plot")
plt.grid(True)
plt.show()


This will display the polar plot with a sinusoidal curve. You can modify the data or customize the plot to suit your needs.

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

Related Posts:

To add a legend to a Matplotlib pie chart, you can follow these steps:Import the necessary libraries: import matplotlib.pyplot as plt Create a list of labels for the pie chart slices: labels = ['Label 1', 'Label 2', 'Label 3'] Create a ...
To create a bar chart using Matplotlib, follow these steps:Import the necessary libraries: import matplotlib.pyplot as plt import numpy as np Create sample data for the x-axis and y-axis values: x = np.array(["A", "B", "C", "D",...
Adding legends to a matplotlib plot is a useful way to label the different elements or data series in a plot. A legend can provide context and make it easier to interpret the chart. Here is how you can add a legend to a matplotlib plot:Import the necessary lib...