0% found this document useful (0 votes)
3 views

MATPLOTLIB

The document provides an overview of the Matplotlib pyplot module, detailing its functionality for creating various types of plots in Python. It includes examples of basic line plots, plotting markers, customizing markers and lines, adding titles and labels, and using subplots for multiple plots in a single figure. Additionally, it explains how to add grid lines and customize their properties.

Uploaded by

bikid25585
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

MATPLOTLIB

The document provides an overview of the Matplotlib pyplot module, detailing its functionality for creating various types of plots in Python. It includes examples of basic line plots, plotting markers, customizing markers and lines, adding titles and labels, and using subplots for multiple plots in a single figure. Additionally, it explains how to add grid lines and customize their properties.

Uploaded by

bikid25585
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 23

MATPLOTLIB

Matplotlib pyplot - Overview and Basic Usage

The pyplot module in Matplotlib provides a powerful set of functions for creating various
types of plots. It is usually imported with the alias plt:

python
Copy code
import matplotlib.pyplot as plt

Key Points about pyplot

 Modularity: Most of the functionality in Matplotlib lies within the pyplot


submodule.
 Aliasing: Importing pyplot as plt is a standard practice for easier reference and
more concise code.

Basic Line Plot Example

This example demonstrates how to draw a simple line in a diagram from one point to another.

python
Copy code
import matplotlib.pyplot as plt
import numpy as np

# Define x and y coordinates


xpoints = np.array([0, 6]) # X-axis points
ypoints = np.array([0, 250]) # Y-axis points

# Plot a line between the defined points


plt.plot(xpoints, ypoints)

# Display the plot


plt.show()

Explanation of Code

1. Importing Libraries:
o matplotlib.pyplot: Used for plotting.
o numpy: Helps create arrays for numerical data.
2. Defining Data Points:
o xpoints and ypoints define the coordinates. Here, (0, 0) is the starting
point and (6, 250) is the endpoint.
3. Plotting the Line:
o plt.plot() function draws a line connecting the defined points.
4. Displaying the Plot:
o plt.show() renders the plot on the screen.

Result
The result will display a simple line plot connecting the points (0, 0) and (6, 250).

Plotting x and y Points

The plot() function in Matplotlib draws points or lines on a diagram.

Example 1: Plotting a Line Between Two Points

python
Copy code
import matplotlib.pyplot as plt
import numpy as np

xpoints = np.array([1, 8])


ypoints = np.array([3, 10])

plt.plot(xpoints, ypoints)
plt.show()

 Plots a line from (1, 3) to (8, 10).

Plotting Without Line

Use 'o' to plot markers without connecting lines.

Example 2: Plotting Only Markers

python
Copy code
import matplotlib.pyplot as plt
import numpy as np

xpoints = np.array([1, 8])


ypoints = np.array([3, 10])

plt.plot(xpoints, ypoints, 'o')


plt.show()

 Plots points at (1, 3) and (8, 10) without lines.

Multiple Points

You can plot multiple points by providing matching arrays for xpoints and ypoints.

Example 3: Plotting Multiple Points

python
Copy code
import matplotlib.pyplot as plt
import numpy as np

xpoints = np.array([1, 2, 6, 8])


ypoints = np.array([3, 8, 1, 10])

plt.plot(xpoints, ypoints)
plt.show()

 Plots a line connecting the points (1, 3), (2, 8), (6, 1), and (8, 10).

Default X-Points

If you omit the x-points, Matplotlib uses default values (0, 1, 2, …).

Example 4: Plotting Without Specifying X-Points

python
Copy code
import matplotlib.pyplot as plt
import numpy as np

ypoints = np.array([3, 8, 1, 10, 5, 7])

plt.plot(ypoints)
plt.show()

 Automatically assigns x-points as [0, 1, 2, 3, 4, 5].

Markers in Matplotlib

Markers help emphasize individual data points on a plot. You can specify the marker type,
size, and color.

Example: Circle Marker

python
Copy code
import matplotlib.pyplot as plt
import numpy as np

ypoints = np.array([3, 8, 1, 10])

plt.plot(ypoints, marker='o')
plt.show()

 Marks each point with a circle.

Example: Star Marker

python
Copy code
plt.plot(ypoints, marker='*')

 Marks each point with a star.


Marker Types

Marker Description
'o' Circle
'*' Star
'.' Point
',' Pixel
'x' X
'X' Filled X
'+' Plus
'P' Filled Plus
's' Square
'D' Diamond
'p' Pentagon
'H' Hexagon
'v' Triangle Down
'>' Triangle Right

Format Strings (fmt)

The fmt parameter allows you to combine marker, line style, and color in one string.

 Syntax: marker|line|color

Example: Circle Marker with Dotted Line

python
Copy code
plt.plot(ypoints, 'o:r')
plt.show()

 Marks points with circles and connects them with a dotted line (':') in red ('r').

Line Types

Line Syntax Description


'-' Solid line
':' Dotted line
'--' Dashed line
'-.' Dashed/Dotted

Color Options

Color Syntax Description


'r' Red
'g' Green
'b' Blue
'c' Cyan
Color Syntax Description
'm' Magenta
'y' Yellow
'k' Black
'w' White

Marker Size

You can adjust marker size using ms or markersize.

Example: Marker Size

python
Copy code
plt.plot(ypoints, marker='o', ms=20)
plt.show()

 Sets the marker size to 20.

Marker Edge and Face Color

 Edge Color: mec or markeredgecolor


 Face Color: mfc or markerfacecolor

Example: Edge Color Red

python
Copy code
plt.plot(ypoints, marker='o', ms=20, mec='r')
plt.show()

 Sets the edge color to red.

Example: Face Color Red

python
Copy code
plt.plot(ypoints, marker='o', ms=20, mfc='r')
plt.show()

 Sets the face color to red.

Example: Both Edge and Face Colors Red

python
Copy code
plt.plot(ypoints, marker='o', ms=20, mec='r', mfc='r')
plt.show()

 Sets both edge and face colors to red.

Hexadecimal Colors
You can also use hexadecimal color values.

Example: Green Color

python
Copy code
plt.plot(ypoints, marker='o', ms=20, mec='#4CAF50', mfc='#4CAF50')
plt.show()

Example: Hotpink Color

python
Copy code
plt.plot(ypoints, marker='o', ms=20, mec='hotpink', mfc='hotpink')
plt.show()

Linestyle and Customization

Changing Line Style

You can change the style of the plotted line using the linestyle or its shorter version ls.

Example: Dotted Line

python
Copy code
import matplotlib.pyplot as plt
import numpy as np

ypoints = np.array([3, 8, 1, 10])

plt.plot(ypoints, linestyle='dotted')
plt.show()

Example: Dashed Line

python
Copy code
plt.plot(ypoints, linestyle='dashed')
plt.show()

Shorter Syntax for Line Style

You can use shorter syntax for the linestyle:

python
Copy code
plt.plot(ypoints, ls=':')

Line Styles
Style Or

'solid' (default) '-'

'dotted' ':'

'dashed' '--'

'dashdot' '-.'

'None' '' or ' '

Line Color

You can change the line color using color or its shorter version c.

Example: Red Line

python
Copy code
plt.plot(ypoints, color='r')
plt.show()

Example: Hexadecimal Color

python
Copy code
plt.plot(ypoints, c='#4CAF50')
plt.show()

Example: Named Color

python
Copy code
plt.plot(ypoints, c='hotpink')
plt.show()

Line Width

You can adjust the line width using linewidth or lw.

Example: Wide Line

python
Copy code
plt.plot(ypoints, linewidth=20.5)
plt.show()

Plotting Multiple Lines

You can plot multiple lines by calling plt.plot() for each line.

Example: Two Lines


python
Copy code
y1 = np.array([3, 8, 1, 10])
y2 = np.array([6, 2, 7, 11])

plt.plot(y1)
plt.plot(y2)
plt.show()

Example: Multiple Lines with X and Y Points

python
Copy code
x1 = np.array([0, 1, 2, 3])
y1 = np.array([3, 8, 1, 10])
x2 = np.array([0, 1, 2, 3])
y2 = np.array([6, 2, 7, 11])

plt.plot(x1, y1, x2, y2)


plt.show()

Adding Labels and Title to a Plot

Create Labels for a Plot

To label the x- and y-axes, you can use the xlabel() and ylabel() functions.

Example: Adding Labels to Axes

python
Copy code
import numpy as np
import matplotlib.pyplot as plt

x = np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])
y = np.array([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])

plt.plot(x, y)

plt.xlabel("Average Pulse")
plt.ylabel("Calorie Burnage")

plt.show()

Create a Title for a Plot

You can set a title for your plot using the title() function.

Example: Adding a Title and Axis Labels

python
Copy code
import numpy as np
import matplotlib.pyplot as plt
x = np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])
y = np.array([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])

plt.plot(x, y)

plt.title("Sports Watch Data")


plt.xlabel("Average Pulse")
plt.ylabel("Calorie Burnage")

plt.show()

Set Font Properties for Title and Labels

You can customize the font properties (e.g., family, color, size) for both the title and the axis
labels by using the fontdict parameter.

Example: Custom Font Properties for Title and Labels

python
Copy code
import numpy as np
import matplotlib.pyplot as plt

x = np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])
y = np.array([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])

font1 = {'family': 'serif', 'color': 'blue', 'size': 20}


font2 = {'family': 'serif', 'color': 'darkred', 'size': 15}

plt.title("Sports Watch Data", fontdict=font1)


plt.xlabel("Average Pulse", fontdict=font2)
plt.ylabel("Calorie Burnage", fontdict=font2)

plt.plot(x, y)
plt.show()

Position the Title

You can position the title using the loc parameter in the title() function. The legal values
for this parameter are 'left', 'right', and 'center' (default).

Example: Title Positioned to the Left

python
Copy code
import numpy as np
import matplotlib.pyplot as plt

x = np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])
y = np.array([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])

plt.title("Sports Watch Data", loc='left')


plt.xlabel("Average Pulse")
plt.ylabel("Calorie Burnage")

plt.plot(x, y)
plt.show()
Adding Grid Lines to a Plot in Matplotlib

Add Grid Lines to a Plot

You can add grid lines to your plot using the grid() function.

Example: Adding Grid Lines

python
Copy code
import numpy as np
import matplotlib.pyplot as plt

x = np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])
y = np.array([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])

plt.title("Sports Watch Data")


plt.xlabel("Average Pulse")
plt.ylabel("Calorie Burnage")

plt.plot(x, y)

plt.grid()

plt.show()

Specify Which Grid Lines to Display

You can choose to display grid lines only for the x-axis, y-axis, or both axes by using the
axis parameter in the grid() function. The valid values for this parameter are 'x', 'y', and
'both' (the default).

Example: Display Grid Lines Only for the x-axis

python
Copy code
import numpy as np
import matplotlib.pyplot as plt

x = np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])
y = np.array([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])

plt.title("Sports Watch Data")


plt.xlabel("Average Pulse")
plt.ylabel("Calorie Burnage")

plt.plot(x, y)

plt.grid(axis='x')

plt.show()

Example: Display Grid Lines Only for the y-axis


python
Copy code
import numpy as np
import matplotlib.pyplot as plt

x = np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])
y = np.array([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])

plt.title("Sports Watch Data")


plt.xlabel("Average Pulse")
plt.ylabel("Calorie Burnage")

plt.plot(x, y)

plt.grid(axis='y')

plt.show()

Set Line Properties for the Grid

You can customize the grid line properties using the color, linestyle, and linewidth
parameters in the grid() function.

Example: Customize Grid Line Properties

python
Copy code
import numpy as np
import matplotlib.pyplot as plt

x = np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])
y = np.array([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])

plt.title("Sports Watch Data")


plt.xlabel("Average Pulse")
plt.ylabel("Calorie Burnage")

plt.plot(x, y)

plt.grid(color='green', linestyle='--', linewidth=0.5)

plt.show()

This customizes the grid to display green dashed lines with a width of 0.5.

Displaying Multiple Plots in Matplotlib using subplot()

Draw 2 Plots Side by Side

The subplot() function allows you to create multiple plots in a single figure by specifying
the number of rows, columns, and the index of the current plot.

Example: 2 Plots Side by Side

python
Copy code
import matplotlib.pyplot as plt
import numpy as np

# Plot 1
x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])

plt.subplot(1, 2, 1) # 1 row, 2 columns, first plot


plt.plot(x, y)

# Plot 2
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])

plt.subplot(1, 2, 2) # 1 row, 2 columns, second plot


plt.plot(x, y)

plt.show()

Layout Description:

 The first argument (1) represents the number of rows.


 The second argument (2) represents the number of columns.
 The third argument (1 for the first plot and 2 for the second plot) represents the
position of the plot.

Draw 2 Plots Vertically

You can arrange the plots vertically (one on top of the other) by adjusting the row and
column arguments.

Example: 2 Plots on Top of Each Other

python
Copy code
import matplotlib.pyplot as plt
import numpy as np

# Plot 1
x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])

plt.subplot(2, 1, 1) # 2 rows, 1 column, first plot


plt.plot(x, y)

# Plot 2
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])

plt.subplot(2, 1, 2) # 2 rows, 1 column, second plot


plt.plot(x, y)

plt.show()
Draw 6 Plots in a 2x3 Grid

You can also create more complex layouts, such as 2 rows and 3 columns for 6 plots.

Example: 6 Plots in a Grid

python
Copy code
import matplotlib.pyplot as plt
import numpy as np

x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])

plt.subplot(2, 3, 1)
plt.plot(x, y)

plt.subplot(2, 3, 2)
plt.plot(x, y * 2)

plt.subplot(2, 3, 3)
plt.plot(x, y * 3)

plt.subplot(2, 3, 4)
plt.plot(x, y * 4)

plt.subplot(2, 3, 5)
plt.plot(x, y * 5)

plt.subplot(2, 3, 6)
plt.plot(x, y * 6)

plt.show()

Adding Titles to Plots

You can add individual titles for each subplot using the title() function.

Example: Titles for Each Plot

python
Copy code
import matplotlib.pyplot as plt
import numpy as np

# Plot 1
x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])

plt.subplot(1, 2, 1)
plt.plot(x, y)
plt.title("SALES")

# Plot 2
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])
plt.subplot(1, 2, 2)
plt.plot(x, y)
plt.title("INCOME")

plt.show()

Adding a Super Title to the Entire Figure

You can use suptitle() to add a title to the whole figure, which applies to all the subplots.

Example: Super Title for the Entire Figure

python
Copy code
import matplotlib.pyplot as plt
import numpy as np

# Plot 1
x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])

plt.subplot(1, 2, 1)
plt.plot(x, y)
plt.title("SALES")

# Plot 2
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])

plt.subplot(1, 2, 2)
plt.plot(x, y)
plt.title("INCOME")

plt.suptitle("MY SHOP") # Super title for the whole figure


plt.show()

This will place the title "MY SHOP" above both the "SALES" and "INCOME" subplots.

he content you've shared provides a comprehensive guide to creating scatter plots using
Matplotlib's pyplot module. Here's a summary of key points:

1. Basic Scatter Plot

To create a basic scatter plot, use the scatter() function, where:

 x and y are arrays representing the data points on the x- and y-axes. Example:

python
Copy code
import matplotlib.pyplot as plt
import numpy as np

x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])
plt.scatter(x, y)
plt.show()

2. Multiple Plots

You can plot multiple datasets on the same figure by calling scatter() multiple times.
Example:

python
Copy code
# Day 1 data
plt.scatter(x1, y1)
# Day 2 data
plt.scatter(x2, y2)
plt.show()

3. Customizing Colors

 Single Color: Use the color argument for a single color. Example:

python
Copy code
plt.scatter(x, y, color='hotpink')

 Custom Color for Each Dot: Use the c argument to specify an array of colors for
each dot. Example:

python
Copy code
colors = np.array(["red", "green", "blue", ...])
plt.scatter(x, y, c=colors)

4. Colormap

To use a continuous range of colors, you can apply a colormap with the cmap argument.
Example:

python
Copy code
colors = np.array([0, 10, 20, 30, ...])
plt.scatter(x, y, c=colors, cmap='viridis')
plt.colorbar()
plt.show()

5. Adjusting Size

 The s argument controls the size of the dots. It requires an array of the same length as
x and y. Example:

python
Copy code
sizes = np.array([20, 50, 100, ...])
plt.scatter(x, y, s=sizes)
6. Alpha (Transparency)

You can adjust the transparency of dots with the alpha argument. The value ranges from 0
(completely transparent) to 1 (completely opaque). Example:

python
Copy code
plt.scatter(x, y, s=sizes, alpha=0.5)

7. Combining Color, Size, and Alpha

You can combine color maps, different sizes, and transparency for enhanced visualization.
Example:

python
Copy code
x = np.random.randint(100, size=(100))
y = np.random.randint(100, size=(100))
colors = np.random.randint(100, size=(100))
sizes = 10 * np.random.randint(100, size=(100))

plt.scatter(x, y, c=colors, s=sizes, alpha=0.5, cmap='nipy_spectral')


plt.colorbar()
plt.show()

This flexibility allows you to tailor scatter plots to your specific data and visualization needs.

Matplotlib Bars

Creating Bars

With Pyplot, the bar() function is used to create vertical bar graphs, and the barh() function
is used for horizontal bar graphs.

Example (Vertical Bars):

python
Copy code
import matplotlib.pyplot as plt
import numpy as np

x = np.array(["A", "B", "C", "D"])


y = np.array([3, 8, 1, 10])

plt.bar(x, y)
plt.show()

This draws 4 vertical bars, each representing a category (A, B, C, D) with corresponding
values (3, 8, 1, 10).

Horizontal Bars
To create horizontal bars, use the barh() function.

Example (Horizontal Bars):

python
Copy code
import matplotlib.pyplot as plt
import numpy as np

x = np.array(["A", "B", "C", "D"])


y = np.array([3, 8, 1, 10])

plt.barh(x, y)
plt.show()

Customizing Bar Colors

You can customize the colors of the bars using the color argument in both bar() and
barh().

Example (Red Bars):

python
Copy code
import matplotlib.pyplot as plt
import numpy as np

x = np.array(["A", "B", "C", "D"])


y = np.array([3, 8, 1, 10])

plt.bar(x, y, color="red")
plt.show()

Example (Hot Pink Bars):

python
Copy code
import matplotlib.pyplot as plt
import numpy as np

x = np.array(["A", "B", "C", "D"])


y = np.array([3, 8, 1, 10])

plt.bar(x, y, color="hotpink")
plt.show()

You can also use Hexadecimal color values.

Example (Green Bars using Hex):

python
Copy code
import matplotlib.pyplot as plt
import numpy as np
x = np.array(["A", "B", "C", "D"])
y = np.array([3, 8, 1, 10])

plt.bar(x, y, color="#4CAF50")
plt.show()

Bar Width

You can adjust the width of the bars using the width argument for vertical bars and the
height argument for horizontal bars.

Example (Thin Bars):

python
Copy code
import matplotlib.pyplot as plt
import numpy as np

x = np.array(["A", "B", "C", "D"])


y = np.array([3, 8, 1, 10])

plt.bar(x, y, width=0.1)
plt.show()

The default width is 0.8.

Example (Thin Horizontal Bars):

python
Copy code
import matplotlib.pyplot as plt
import numpy as np

x = np.array(["A", "B", "C", "D"])


y = np.array([3, 8, 1, 10])

plt.barh(x, y, height=0.1)
plt.show()

The default height is 0.8.

You can use these examples to customize and display bar plots with various properties like
color, width, and orientation in your data visualizations.

Matplotlib Histograms

Histogram Overview

A histogram is a graphical representation that shows the distribution of numerical data. It


represents the number of observations within a given range (interval or bin). For example, in
a survey about the height of 250 people, a histogram can visually display how many people
fall into certain height ranges, such as 140–145 cm, 145–150 cm, and so on.

Create a Histogram in Matplotlib

To create a histogram in Matplotlib, we use the hist() function. The hist() function takes
an array of numbers as an argument and plots the histogram based on the data.

Example: Generate Random Data

To simulate a data distribution (e.g., heights), we can use NumPy to generate a normal
distribution of values. The example below generates 250 random values with a mean of 170
and a standard deviation of 10.

python
Copy code
import numpy as np

# Generate random data with mean 170 and std deviation 10


x = np.random.normal(170, 10, 250)

print(x) # This prints the generated data (e.g., heights)

This will output an array of 250 random heights that concentrate around 170 with a standard
deviation of 10.

Plotting the Histogram

We can now use Matplotlib's hist() function to plot the histogram of this data.

python
Copy code
import matplotlib.pyplot as plt
import numpy as np

# Generate random data


x = np.random.normal(170, 10, 250)

# Plot the histogram


plt.hist(x)
plt.show()

This will display a histogram where the x-axis represents the height intervals (bins) and the y-
axis represents the frequency (number of people) in each interval. The hist() function
automatically divides the data into bins and displays the distribution of the data.

Customizing Histograms

Specifying the Number of Bins


You can specify the number of bins (intervals) using the bins argument. This can help
control the granularity of the histogram.

python
Copy code
plt.hist(x, bins=20) # Specifies 20 bins
plt.show()

Adding Labels and Title

To make your histogram more informative, you can add labels and a title.

python
Copy code
plt.hist(x, bins=20)
plt.title('Height Distribution')
plt.xlabel('Height (cm)')
plt.ylabel('Frequency')
plt.show()

This will add a title to the histogram and labels to the x and y axes.

Matplotlib Pie Charts

Creating Pie Charts


To create pie charts in Matplotlib, the pie() function is used, which plots wedges
representing data values.

Example: Simple Pie Chart


python
Copy code
import matplotlib.pyplot as plt
import numpy as np

y = np.array([35, 25, 25, 15])

plt.pie(y)
plt.show()

This pie chart shows 4 wedges, one for each value in the array [35, 25, 25, 15]. The
default behavior is to start the first wedge from the x-axis and move counterclockwise.

Labels

To add labels to each wedge, use the labels parameter:

python
Copy code
import matplotlib.pyplot as plt
import numpy as np

y = np.array([35, 25, 25, 15])


mylabels = ["Apples", "Bananas", "Cherries", "Dates"]
plt.pie(y, labels=mylabels)
plt.show()

This will display the pie chart with labels for each wedge.

Start Angle

By default, the chart starts from the x-axis (0 degrees). You can change the starting point
using the startangle parameter:

python
Copy code
import matplotlib.pyplot as plt
import numpy as np

y = np.array([35, 25, 25, 15])


mylabels = ["Apples", "Bananas", "Cherries", "Dates"]

plt.pie(y, labels=mylabels, startangle=90)


plt.show()

This will rotate the pie chart, starting at 90 degrees.

Exploding Wedges

To make one of the wedges stand out, you can "explode" it using the explode parameter:

python
Copy code
import matplotlib.pyplot as plt
import numpy as np

y = np.array([35, 25, 25, 15])


mylabels = ["Apples", "Bananas", "Cherries", "Dates"]
myexplode = [0.2, 0, 0, 0] # "Apples" wedge will explode

plt.pie(y, labels=mylabels, explode=myexplode)


plt.show()

This will pull the "Apples" wedge out by 0.2.

Shadow

You can add a shadow to the pie chart by setting the shadow parameter to True:

python
Copy code
import matplotlib.pyplot as plt
import numpy as np

y = np.array([35, 25, 25, 15])


mylabels = ["Apples", "Bananas", "Cherries", "Dates"]
myexplode = [0.2, 0, 0, 0]
plt.pie(y, labels=mylabels, explode=myexplode, shadow=True)
plt.show()

This will add a shadow effect to the pie chart.

Colors

To customize the colors of the wedges, you can use the colors parameter, which accepts a
list of color values:

python
Copy code
import matplotlib.pyplot as plt
import numpy as np

y = np.array([35, 25, 25, 15])


mylabels = ["Apples", "Bananas", "Cherries", "Dates"]
mycolors = ["black", "hotpink", "b", "#4CAF50"]

plt.pie(y, labels=mylabels, colors=mycolors)


plt.show()

Here, the wedges will be colored as specified.

You can also use color shortcuts:

 'r' - Red
 'g' - Green
 'b' - Blue
 'c' - Cyan
 'm' - Magenta
 'y' - Yellow
 'k' - Black
 'w' - White

Legend

To add a legend to the pie chart, use the legend() function:

python
Copy code
import matplotlib.pyplot as plt
import numpy as np

y = np.array([35, 25, 25, 15])


mylabels = ["Apples", "Bananas", "Cherries", "Dates"]

plt.pie(y, labels=mylabels)
plt.legend()
plt.show()

Legend With Header


To add a header to the legend, you can include the title parameter in the legend()
function:

python
Copy code
import matplotlib.pyplot as plt
import numpy as np

y = np.array([35, 25, 25, 15])


mylabels = ["Apples", "Bananas", "Cherries", "Dates"]

plt.pie(y, labels=mylabels)
plt.legend(title="Four Fruits:")
plt.show()

This will display the legend with the specified title "Four Fruits:".

You might also like