0% found this document useful (0 votes)
29 views11 pages

Mat Plot Lib

Uploaded by

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

Mat Plot Lib

Uploaded by

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

Matplotlib

The basic syntax for creating a scatter plot :

plt.scatter(x, y, s=None, c=None, marker=None, alpha=None,


linewidths=None, edgecolors=None, **kwargs)
Key parameters:

• x , y : These are the coordinates of the data points. Can be arrays or lists.
• s : This parameter controls the size of the markers. It can be a single scalar value (to set
all markers to the same size) or an array/list of the same length as x and y (to set
individual marker sizes).
• c : This parameter controls the color of the markers. It can be a single color string, a list
of color strings, or an array of numerical values that will be mapped to colors using a
colormap.
• marker : This parameter specifies the marker style .
• alpha : This parameter controls the transparency of the markers (a value between 0 and
1).
• linewidths : This parameter sets the width of the marker edges.
• edgecolors : This parameter sets the color of the marker edges.

List of Marker style commonly used:

• . : point marker
• , : pixel marker
• o : circle marker
• v : triangle_down marker
• ^ : triangle_up marker
• < : triangle_left marker
• > : triangle_right marker
• s : square marker
• p : pentagon marker
• * : star marker
• h : hexagon1 marker
• H : hexagon2 marker
• D: diamond marker
• d: thin_diamond marker
• P: plus (filled) marker
• X: x (filled) marker
• |: vertical line marker
• _: horizontal line marker
Example:

x = [1, 2, 3, 4]
y = [5, 4, 6, 2]
sizes = [50, 100, 150, 200]
colors = ['red', 'blue', 'green', 'purple']

plt.scatter(x, y, s=sizes, c=colors, marker='o')


plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('My Scatter Plot')
plt.show()

How to label axis and Title


You can label the x-axis and y-axis of your scatter plot using
the plt.xlabel() and plt.ylabel() functions, respectively. Name of title using plt.title()
You just pass the desired label as a string to each function.

Example

import matplotlib.pyplot as plt

x = [1, 2, 3, 4]
y = [5, 4, 6, 2]
sizes = [100, 100, 100, 100] # Keeping sizes the same for clarity

# Using a list of colors for the 'c' argument


colors = ['red', 'blue', 'red', 'blue'] # Example with two colors
plt.scatter(x, y, marker='*', s=sizes, c=colors) # Using '*' for star
markers

# Adding labels to the x and y axes and the title


plt.xlabel('X-axis Label')
plt.ylabel('Y-axis Label')
plt.title('Scatter Plot with Different Marker Style and Colors')
plt.show()

Line Plot
Points are plotting along a curve. This can be done by plt.plot() in matplotlib to create line
plots. It connects data points with lines, which is useful for showing trends or the relationship
between variables over a continuous range.

Syntax:
plt.plot(*args, scalex=True, scaley=True, **kwargs)

Explaination:

• *args : This is a special syntax in Python. The single asterisk ( * ) before args means
that the function can accept a variable number of positional arguments. These arguments
will be collected into a tuple named args inside the function. For plt.plot() , these
positional arguments are typically the x and y data values you want to plot, and optionally
format strings (like 'r--' ). You can pass multiple pairs of x , y data this way
(e.g., plt.plot(x1, y1, x2, y2) ).
• scalex=True , scaley=True : These are keyword arguments with default values.
o scalex : If True , the x-axis limits are automatically scaled to the data.
o scaley : If True , the y-axis limits are automatically scaled to the data. You can
set these to False if you want to manually control the axis limits.

Example:

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [2, 4, 1, 5, 3]

# Create a line plot


plt.plot(x, y)

plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Simple Line Plot')
plt.grid(True) # Add a grid for better readability
plt.show()

Now using numpy.linspace().

numpy.linspace() is a function in the NumPy library that is used to create a sequence of


evenly spaced numbers over a specified interval.

Here's the basic syntax:

numpy.linspace(start, stop, num=50, endpoint=True)


Key arguments:

• start : The starting value of the sequence.


• stop : The end value of the sequence.
• num : The number of samples to generate (defaults to 50).
• endpoint : If True (default), stop is the last sample. If False, stop is not included.

Example
import numpy as np
import matplotlib.pyplot as plt

# Generate x values using linspace


# Create 100 points between 0 and 2*pi
x_values = np.linspace(0, 2 * np.pi, 100)

# Calculate the corresponding y values using a function (e.g., sine)


y_values = np.sin(x_values)

# Plot the function


plt.plot(x_values, y_values)

plt.xlabel('x')
plt.ylabel('sin(x)')
plt.title('Plot of the Sine Function using linspace')
plt.grid(True)
plt.show()

Example:

import matplotlib.pyplot as plt


import numpy as np

x = np.linspace(0, 10, 50)


y = np.sin(x)

plt.plot(x, y, color='blue', linestyle='--', linewidth=2, marker='o',


markersize=5)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Customized Line Plot')
plt.grid(True)
plt.show()

Use of legends to make graph look attractive


plt.legend() in Matplotlib is used to display a legend on the plot.

A legend is a small box that helps identify the different lines or markers plotted, especially when
you have multiple datasets or categories on the same graph. It associates the visual style of
each plotted element (like a line color or marker shape) with a descriptive label.
For plt.legend() to work, you need to:
1. Provide a label argument when you create each plot element (e.g.,
in plt.plot() or plt.scatter() ).
2. Call plt.legend() after all the plot elements with labels have been created and
before plt.show() .

Example

import numpy as np
import matplotlib.pyplot as plt

# Generate x values
x = np.linspace(0, 10, 100)

# Generate y values for two different functions


y1 = np.sin(x)
y2 = np.cos(x)

# Plot the first graph with a label


plt.plot(x, y1, label='Sine wave', color='blue')

# Plot the second graph with a label


plt.plot(x, y2, label='Cosine wave', color='red', linestyle='--')

# Add labels and title


plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Sine and Cosine Waves')

# Display the legend


plt.legend()

# Add a grid
plt.grid(True)

# Show the plot


plt.show()

Subplots
"Subplots" in Matplotlib allow you to create multiple plots (or axes) within a single figure. This is
really useful for comparing different visualizations or showing related data side-by-side.

Here's the basic idea:


fig, axes = plt.subplots(nrows, ncols)

• nrows : The number of rows of subplots you want.


• ncols : The number of columns of subplots you want.
• fig : The figure object, which is the overall container for your plots.
• axes : A NumPy array containing the individual axes objects (the actual plots).

You can then access each subplot using array indexing (e.g., axes[0, 0] for the top-left
subplot in a 2x2 grid, or axes[0] if you only have one row or one column).

1. The Figure Object ( fig ): This is the overall container for your plot. Think of it as the
window or canvas where all the subplots will be drawn. You can use the fig object to do
things like set the overall title of the figure, save the figure to a file, or adjust its size.
2. The Axes Object(s) ( axes ): This represents the individual plot(s) within the figure. If you
create a single subplot ( plt.subplots(1, 1) ), axes will be a single Axes object. If
you create multiple subplots (e.g., plt.subplots(2, 2) for a 2x2 grid), axes will be a
NumPy array containing multiple Axes objects, one for each subplot. These are the
objects you'll use to draw your data (e.g., axes[0, 0].plot(x, y) ).

Example:
import numpy as np
import matplotlib.pyplot as plt

# Create a figure with 2 rows and 1 column of subplots


fig, axes = plt.subplots(2, 1, figsize=(6, 8)) # Adjusting figsize for
vertical layout

# Generate some data


x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = x**2

# Plot on the first subplot (top) - access with a single index as it's
a 1D array
axes[0].plot(x, y1, color='blue')
axes[0].set_title('Sine Wave')
axes[0].set_xlabel('X-axis')
axes[0].set_ylabel('Y-axis')
axes[0].grid(True)

# Plot on the second subplot (bottom) - access with a single index


axes[1].plot(x, y2, color='red')
axes[1].set_title('x^2 Function')
axes[1].set_xlabel('X-axis')
axes[1].set_ylabel('Y-axis')
axes[1].grid(True)

# Add a title to the entire figure


fig.suptitle('Vertical Subplots', fontsize=16)
# Adjust layout to prevent titles/labels from overlapping
plt.tight_layout(rect=[0, 0.03, 1, 0.95]) # Adjust layout to make space
for suptitle

# Show the plot


plt.show()

• plt.tight_layout() : This function automatically adjusts subplot parameters for a


tight layout. Its purpose is to prevent labels, titles, and other elements from overlapping,
making the plot more readable. By default, it tries to make the spacing between subplots
and the padding around them just enough to accommodate all the elements without
collision.
• plt.tight_layout() : This function automatically adjusts subplot parameters for a
tight layout. Its purpose is to prevent labels, titles, and other elements from overlapping,
making the plot more readable. By default, it tries to make the spacing between subplots
and the padding around them just enough to accommodate all the elements without
collision.
• rect=[0, 0.03, 1, 0.95] : This is the rect keyword argument, which stands for
"rectangle". It's a tuple or list of four values [left, bottom, right, top] that
specify the normalized coordinates of the rectangle within the figure where the tight
layout adjustment should be applied. The values are in the range of 0 to 1, where (0,0) is
the bottom-left corner of the figure and (1,1) is the top-right corner.
In this specific case:

o left=0 : The left edge of the rectangle is at the very left of the figure.
o bottom=0.03 : The bottom edge of the rectangle is slightly above the very
bottom of the figure (3% of the figure height from the bottom). This is often done
to leave space at the bottom for a potential suptitle or other figure-level elements.
o right=1 : The right edge of the rectangle is at the very right of the figure.
o top=0.95 : The top edge of the rectangle is slightly below the very top of the
figure (95% of the figure height from the bottom). This is done to leave space at
the top, especially when you have a figure-level title set using fig.suptitle()

Example: Four graph


import numpy as np
import matplotlib.pyplot as plt

# Create a figure with a 2x2 grid of subplots


fig, axes = plt.subplots(2, 2, figsize=(10, 8))

# Generate some data


x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.tan(x)
y4 = x**2
# Plot on each subplot
axes[0, 0].plot(x, y1)
axes[0, 0].set_title('Sine')

axes[0, 1].plot(x, y2, color='red')


axes[0, 1].set_title('Cosine')

# Note: For tan, we'll limit the x-range to avoid infinities


axes[1, 0].plot(np.linspace(-np.pi/2 + 0.1, np.pi/2 - 0.1, 100),
np.tan(np.linspace(-np.pi/2 + 0.1, np.pi/2 - 0.1, 100)), color='green')
axes[1, 0].set_title('Tangent')
axes[1, 0].set_ylim(-10, 10) # Set y-limits for tangent

axes[1, 1].plot(x, y4, color='purple')


axes[1, 1].set_title('x^2')

# Add a title to the entire figure


fig.suptitle('Four Different Plots', fontsize=16)

# Adjust layout
plt.tight_layout(rect=[0, 0.3, 0, 0.95]) # Adjust layout to make space
for suptitle

# Show the plot


plt.show()

Bar Graph
The basic syntax for plt.bar() is

plt.bar(x, height, **kwargs) .


Here's a breakdown of the key parameters:

• x : The x-coordinates of the bars. This can be a list of strings (for categorical data) or
numbers.
• height : The height of the bars. This should be a list or array of numerical values,
corresponding to the x values.
• **kwargs : Optional keyword arguments to customize the appearance of the bars and
the plot. Some common ones include:
o width : The width of the bars (default is 0.8).
o color : The color of the bars. Can be a single color string (e.g., 'blue', 'red') or a
list of colors for each bar.
o edgecolor : The color of the bar edges.
o linewidth : The width of the bar edges.
o tick_label : Labels for the x-axis ticks. If x is numerical, you can use this to
provide custom labels.
o label : A label for the bar series, which can be used in a legend.

Example:

import matplotlib.pyplot as plt


import numpy as np

# Sample data
categories = ['A', 'B', 'C', 'D', 'E']
values = np.array([5, 7, 3, 8, 6])

# Create the bar plot with customizations


plt.bar(categories, values, color=['skyblue', 'lightgreen', 'salmon',
'gold', 'c']) # color

# Add titles and labels


plt.title('Sample Bar Plot and Colors')
plt.xlabel('Categories')
plt.ylabel('Values')

# Show the plot


plt.show()

Example: With legends

import matplotlib.pyplot as plt


import numpy as np

# Sample data
categories = ['A', 'B', 'C', 'D', 'E']
values = np.array([5, 7, 3, 8, 6])
l=["r","b","o","p","y"]

# Create the bar plot with customizations


plt.figure(figsize=(8, 6))
plt.bar(categories, values, color=['skyblue', 'lightgreen', 'salmon',
'gold', 'c'],
edgecolor='black', label=l)

# Add titles and labels


plt.title('Sample Bar Plot with Colors')
plt.xlabel('Categories')
plt.ylabel('Values')

# Add a legend
plt.legend()

# Show the plot


plt.show()

Bar Labels
plt.bar_label() is a useful function for adding labels to the top of your bars in a bar plot.
This makes it easier to read the exact value of each bar directly on the plot.
Syntax:
plt.bar_label(container, labels=None, fmt='%g',
label_type='vertical', padding=5, **kwargs)

• container : This is the container object returned by plt.bar() .


• labels : An optional list of strings to use as labels. If not provided, the function will use
the bar heights as labels.
• fmt : A format string for the labels (default is '%g').
• label_type : The type of label alignment ('vertical' or 'horizontal').
• padding : The distance between the top of the bar and the label.
• **kwargs : Additional keyword arguments for customizing the label text properties
(e.g., fontsize , color ).

Example

import matplotlib.pyplot as plt


import numpy as np

# Data for the bar plot


categories = ['A', 'B', 'C']
values = [10, 25, 15]

# Create the bar plot


plt.figure(figsize=(6,4)) # Added figure size for better readability
bars = plt.bar(categories, values) # Store the bars to iterate over
them

# Add titles and labels


plt.title('Simple Bar Plot with Labels') # Updated title
plt.xlabel('Categories')
plt.ylabel('Values')

plt.bar_label(bars,fmt="%g")

# Show the plot


plt.show()
# Data for the bar plot
categories = ['A', 'B', 'C']
values = [10, 25, 15]
# Custom text labels for each bar
custom_labels = ['First', 'Second', 'Third']

# Create the bar plot


plt.figure(figsize=(6,4)) # Added figure size for better readability
bars = plt.bar(categories, values) # Store the bars to iterate over
them

# Add titles and labels


plt.title('Simple Bar Plot with Custom Labels') # Updated title
plt.xlabel('Categories')
plt.ylabel('Values')

# Add custom labels to the bars


for i, bar in enumerate(bars):
yval = bar.get_height()
plt.text(bar.get_x() + bar.get_width()/2.0, yval, custom_labels[i],
va='bottom', ha='center') # Add custom text label

# Show the plot


plt.show()

You might also like