MATPLOTLIB
MATPLOTLIB
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
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
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).
python
Copy code
import matplotlib.pyplot as plt
import numpy as np
plt.plot(xpoints, ypoints)
plt.show()
python
Copy code
import matplotlib.pyplot as plt
import numpy as np
Multiple Points
You can plot multiple points by providing matching arrays for xpoints and ypoints.
python
Copy code
import matplotlib.pyplot as plt
import numpy as np
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, …).
python
Copy code
import matplotlib.pyplot as plt
import numpy as np
plt.plot(ypoints)
plt.show()
Markers in Matplotlib
Markers help emphasize individual data points on a plot. You can specify the marker type,
size, and color.
python
Copy code
import matplotlib.pyplot as plt
import numpy as np
plt.plot(ypoints, marker='o')
plt.show()
python
Copy code
plt.plot(ypoints, marker='*')
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
The fmt parameter allows you to combine marker, line style, and color in one string.
Syntax: marker|line|color
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
Color Options
Marker Size
python
Copy code
plt.plot(ypoints, marker='o', ms=20)
plt.show()
python
Copy code
plt.plot(ypoints, marker='o', ms=20, mec='r')
plt.show()
python
Copy code
plt.plot(ypoints, marker='o', ms=20, mfc='r')
plt.show()
python
Copy code
plt.plot(ypoints, marker='o', ms=20, mec='r', mfc='r')
plt.show()
Hexadecimal Colors
You can also use hexadecimal color values.
python
Copy code
plt.plot(ypoints, marker='o', ms=20, mec='#4CAF50', mfc='#4CAF50')
plt.show()
python
Copy code
plt.plot(ypoints, marker='o', ms=20, mec='hotpink', mfc='hotpink')
plt.show()
You can change the style of the plotted line using the linestyle or its shorter version ls.
python
Copy code
import matplotlib.pyplot as plt
import numpy as np
plt.plot(ypoints, linestyle='dotted')
plt.show()
python
Copy code
plt.plot(ypoints, linestyle='dashed')
plt.show()
python
Copy code
plt.plot(ypoints, ls=':')
Line Styles
Style Or
'dotted' ':'
'dashed' '--'
'dashdot' '-.'
Line Color
You can change the line color using color or its shorter version c.
python
Copy code
plt.plot(ypoints, color='r')
plt.show()
python
Copy code
plt.plot(ypoints, c='#4CAF50')
plt.show()
python
Copy code
plt.plot(ypoints, c='hotpink')
plt.show()
Line Width
python
Copy code
plt.plot(ypoints, linewidth=20.5)
plt.show()
You can plot multiple lines by calling plt.plot() for each line.
plt.plot(y1)
plt.plot(y2)
plt.show()
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])
To label the x- and y-axes, you can use the xlabel() and ylabel() functions.
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()
You can set a title for your plot using the title() function.
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.show()
You can customize the font properties (e.g., family, color, size) for both the title and the axis
labels by using the fontdict parameter.
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.show()
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).
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.show()
Adding Grid Lines to a Plot in Matplotlib
You can add grid lines to your plot using the grid() function.
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.grid()
plt.show()
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).
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.grid(axis='x')
plt.show()
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.grid(axis='y')
plt.show()
You can customize the grid line properties using the color, linestyle, and linewidth
parameters in the grid() function.
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.show()
This customizes the grid to display green dashed lines with a width of 0.5.
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.
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])
# Plot 2
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])
plt.show()
Layout Description:
You can arrange the plots vertically (one on top of the other) by adjusting the row and
column arguments.
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])
# Plot 2
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])
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.
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()
You can add individual titles for each subplot using the title() function.
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()
You can use suptitle() to add a title to the whole figure, which applies to all the subplots.
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")
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:
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)
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))
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.
python
Copy code
import matplotlib.pyplot as plt
import numpy as np
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.
python
Copy code
import matplotlib.pyplot as plt
import numpy as np
plt.barh(x, y)
plt.show()
You can customize the colors of the bars using the color argument in both bar() and
barh().
python
Copy code
import matplotlib.pyplot as plt
import numpy as np
plt.bar(x, y, color="red")
plt.show()
python
Copy code
import matplotlib.pyplot as plt
import numpy as np
plt.bar(x, y, color="hotpink")
plt.show()
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.
python
Copy code
import matplotlib.pyplot as plt
import numpy as np
plt.bar(x, y, width=0.1)
plt.show()
python
Copy code
import matplotlib.pyplot as plt
import numpy as np
plt.barh(x, y, height=0.1)
plt.show()
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
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.
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
This will output an array of 250 random heights that concentrate around 170 with a standard
deviation of 10.
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
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
python
Copy code
plt.hist(x, bins=20) # Specifies 20 bins
plt.show()
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.
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
python
Copy code
import matplotlib.pyplot as plt
import numpy as np
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
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
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
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
'r' - Red
'g' - Green
'b' - Blue
'c' - Cyan
'm' - Magenta
'y' - Yellow
'k' - Black
'w' - White
Legend
python
Copy code
import matplotlib.pyplot as plt
import numpy as np
plt.pie(y, labels=mylabels)
plt.legend()
plt.show()
python
Copy code
import matplotlib.pyplot as plt
import numpy as np
plt.pie(y, labels=mylabels)
plt.legend(title="Four Fruits:")
plt.show()
This will display the legend with the specified title "Four Fruits:".