Showing posts with label pyplot. Show all posts
Showing posts with label pyplot. Show all posts

Friday, 3 November 2023

Plotting Polygons with Pyplot

Using plt.Polygon method, we can plot a polygon. A polygon can be a triangle, rectangle, square etc., We can draw both closed and open polygons.

 

Signature

matplotlib.pyplot.Polygon(vertices, closed=True, fill=True, **kwargs)

 

vertices: Point to list of vertexes

closed: If it is set to True, then the polygon is closed, that means the last vertex will be connected to the first vertex to close the polygon.

fill: If fillis set to True, the polygon will be filled with the color specified by the color parameter.

**kwargs: These are the additional keyword arguments used to control the appearance of the polygon, such as the color, line width, and line style.

 

Example: Draw a triangle

# Define the vertices of the triangle
triangle_vertices = np.array([
    [0, 0],
    [4, 0],
    [2, 3]
])
# Create a scatter plot of the triangle vertices
plt.scatter(triangle_vertices[:, 0], triangle_vertices[:, 1], c='blue', marker='o', label='Triangle')
# Connect the vertices to form the triangle
triangle = plt.Polygon(triangle_vertices, closed=True, fill=True, color='blue', alpha=0.5)
plt.gca().add_patch(triangle)

 

Example: Draw a square

# Define the vertices of the Square
square_vertices = np.array([
    [5, 0],
    [5, 5],
    [10, 5],
    [10, 0]
])
# Create a scatter plot of the triangle vertices
plt.scatter(square_vertices[:, 0], square_vertices[:, 1], c='green', marker='o', label='Square')
square = plt.Polygon(square_vertices, closed=True, fill=None, color='green', linestyle='--')
plt.gca().add_patch(square)

 

Example: Draw a Pentagon

pentagon_vertices = np.array([
    [1, 5],
    [1, 7],
    [3, 7],
    [3, 4],
    [2, 4]
])
# Create a scatter plot of the triangle vertices
plt.scatter(pentagon_vertices[:, 0], pentagon_vertices[:, 1], c='red', marker='o', label='Pentagon')
pentagon = plt.Polygon(pentagon_vertices, closed=False, fill=False, color='green')
plt.gca().add_patch(pentagon)

 

'plt.gca()' return the current axis or subplot in a Matplotlib figure when creating or customizing plots. Using 'plt.gca().add_patch' method, we can add various geometric shapes, such as polygons, rectangles, circles, and more, to a plot or axis.

 

Find the below working application.

 

polynomial.py

import matplotlib.pyplot as plt
import numpy as np

# Create a figure with a specific size (width, height)
plt.figure(figsize=(12, 10))

# Define the vertices of the triangle
triangle_vertices = np.array([
    [0, 0],
    [4, 0],
    [2, 3]
])
# Create a scatter plot of the triangle vertices
plt.scatter(triangle_vertices[:, 0], triangle_vertices[:, 1], c='blue', marker='o', label='Triangle')
# Connect the vertices to form the triangle
triangle = plt.Polygon(triangle_vertices, closed=True, fill=True, color='blue', alpha=0.5)
plt.gca().add_patch(triangle)

# Define the vertices of the Square
square_vertices = np.array([
    [5, 0],
    [5, 5],
    [10, 5],
    [10, 0]
])
# Create a scatter plot of the triangle vertices
plt.scatter(square_vertices[:, 0], square_vertices[:, 1], c='green', marker='o', label='Square')
square = plt.Polygon(square_vertices, closed=True, fill=None, color='green', linestyle='--')
plt.gca().add_patch(square)


pentagon_vertices = np.array([
    [1, 5],
    [1, 7],
    [3, 7],
    [3, 4],
    [2, 4]
])
# Create a scatter plot of the triangle vertices
plt.scatter(pentagon_vertices[:, 0], pentagon_vertices[:, 1], c='red', marker='o', label='Pentagon')
pentagon = plt.Polygon(pentagon_vertices, closed=False, fill=False, color='green')
plt.gca().add_patch(pentagon)

# Add labels and legend
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.legend()
plt.title('Polygon')
plt.xticks(np.arange(1, 10))
plt.yticks(np.arange(1, 10))

# Display the plot
plt.show()

 

Output

 



 

 

 

 

Previous                                                    Next                                                    Home

How to add minor ticks to x and y axis?

We add minor ticks to the x and y axes using ax.minorticks_on()

minor_ticks.py

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(1, 10)
y = 10 * x + 123

plt.plot(x, y)

plt.minorticks_on()

# Show the plot
plt.show()

 

 

 

  

Previous                                                    Next                                                    Home

Sunday, 29 October 2023

Adding Grid Lines to Plots in Matplotlib

Using grid method of Pyplot, we can display grid lines on a plot.

Signature

matplotlib.pyplot.grid(b=None, which='major', axis='both', **kwargs)

 

b: If the parameter b is set to True, then it displays grid lines on the plot. If the parameter b is set to False, then grid lines are hidden. By default it is set to None, and the default state depends on  the current state of the grid.

 

which: Specifies which kind of grid lines the settings should apply. Possible values are major, minor and both.

 

axis: It can take one of three values.

1.   both: Apply grid lines to both the axis

2.   x: Apply grid lines to x-axis

3.   y: Apply grid lines to y-axis

 

Apart from this you can specify the arguments like color, linestyle, alpha parameters (alpha parameter control the transparency or opacity of graphical elements).

 

Example 1: Plot grid lines on both x and y axis.

plt.plot(x, y, label='y = 10 * x + 123')

 

add_grid_lines.py

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(1, 10)
y = 10 * x + 123

plt.plot(x, y, label='y = 10 * x + 123')

plt.grid(True)
plt.show()

 

Output

 


Example 2: Add only horizontal grid lines.

plt.grid(True, axis='y')

 

add_horizontal_grid_lines_only.py

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(1, 10)
y = 10 * x + 123

plt.plot(x, y, label='y = 10 * x + 123')

plt.grid(True, axis='y')
plt.show()

Output


 

Example 3: Customize grid line style, color, opacity.

plt.grid(True, linestyle='--', color='red', alpha=0.5)

 

customize_grid_line.py

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(1, 10)
y = 10 * x + 123

plt.plot(x, y, label='y = 10 * x + 123')

plt.grid(True, linestyle='--', color='red', alpha=0.5)
plt.show()

 

Output

 


 

Example 4: ‘which’ parameter example.

 

You need to turn on minor tick by executing below line.

plt.minorticks_on()

 

Find the below working application.

 

which_parameter.py

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(1, 100)
y = 10 * x + 123

plt.plot(x, y)

plt.minorticks_on()

# Customize major gridlines only
plt.grid(True, which='major', linestyle='--', color='red')

# Customize minor gridlines only
plt.grid(True, which='minor', linestyle=':', color='blue')

# Show the plot
plt.show()

Output



 

 

Previous                                                    Next                                                    Home

How to Add Vertical Lines to Plots in Python with Matplotlib?

Using 'axvline' method, we can draw a vertical line on the plot.

Example

plot.axvline(x=100, color='red', label=f'Vertical Line at x={100}')

 

Above statement draws a vertical line at x=100, and applies red color to it.

 

Find the below working application.

 

vertical_line.py

import matplotlib.pyplot as plot
import numpy as np

# Sample data
x = np.arange(1, 100)
y = 10 * x + 123

# Plot the data points
plot.plot(x, y, label='y=10x+123')

median = np.median(x)

plot.axvline(x=median, color='red', label=f'Vertical Line at x={median}')
text = f'This is x={median}'
plot.text(median+15, 1000, text, color='red', fontsize=12, ha='center')

# Set labels and legend
plot.legend()

# Show the plot
plot.show()

 

Output

 


 

Previous                                                    Next                                                    Home

Plotting Horizontal Lines in Matplotlib with Pyplot

Using 'axhline' method, we can draw horizontal line on a plot

Example

plot.axhline(y=100, color='green', label=f'Horizontal Line at y=100')

Above statement draws a horizontal line at y = 100, and applies green color to it.

 

Find the below working applicaiton.

 

horizontal_line.py

import matplotlib.pyplot as plot
import numpy as np

# Sample data
x = np.arange(1, 100)
y = 10 * x + 123


# Plot the data points
plot.plot(x, y, label='y=10x+123')

mean = np.mean(y)
plot.axhline(y=mean, color='green', label=f'Horizontal Line at y={mean}')
text = f'This is y={mean}'
plot.text(30, mean + 10, text, color='red', fontsize=12, ha='center')

# Set labels and legend
plot.legend()

# Show the plot
plot.show()

Output



 

  

Previous                                                    Next                                                    Home

Wednesday, 11 October 2023

Plotting Multiple Graphs in a Single Figure with Python

Subplots are very helpful when you want to display multiple visualizations side by side for comparison in a single figure.

Using 'subplots' method of pyplot, we can create a grid of subplots within a single figure in pyplot.

 

sub_plot_demo.py

import matplotlib.pyplot as plt
import numpy as np

# Create a 2x2 grid of subplots
fig, axs = plt.subplots(nrows=2, ncols=2)
fig.suptitle('Sub plots demo', fontsize=16)

x1 = np.array([2, 3, 5, 7, 11, 13, 17])
y1 = 5 * x1 + 345

x2 = np.array([17, 13, 11, 7, 5, 3, 2])
y2 = 5 * x2 + 345

categories = ['Apple', 'Banana', 'Orange', 'Grapes']
liked_by_count = [120, 45, 32, 87]

# Plot data in each subplot
axs[0, 0].plot(x1, y1)
axs[0, 1].scatter(x2, y2)

axs[1, 0].bar(categories, liked_by_count)
colors = ['r', 'green', '#fedcba', (0, 1, 1), (1, 0, 0, 0.5)]

axs[1, 1].pie(liked_by_count, labels=categories, autopct='%1.1f%%', colors=colors)

# Customize each subplot as needed
axs[0, 0].set_title('Line Plot')
axs[0, 0].set_xlabel('primes')
axs[0, 0].set_ylabel('y=5x+345')

# Customize each subplot as needed
axs[0, 1].set_title('Scatter Plot')
axs[0, 1].set_xlabel('primes')
axs[0, 1].set_ylabel('y=5x+345')

# Add titles, labels, legends, etc., to other subplots similarly

# Adjust layout
plt.tight_layout(rect=[0, 0, 1, 0.95])

# Show the figure
plt.show()

Output



fig, axs = plt.subplots(nrows=2, ncols=2)

Above statement  creates a figure with a 2x2 grid of subplots. The nrows and ncols parameters specify the number of rows and columns in the grid. The fig variable represents the entire figure, while axs is a 2D array of subplot objects.

 

You can access each subplot using indexing, like axs[0, 0], axs[0, 1], and so on. axs[0,0] give you the reference to the plot in first row and first column.

 

plt.tight_layout(rect=[0, 0, 1, 0.95])

Above statement makes sure that the subplots are properly spaced and do not overlap.

 

Previous                                                    Next                                                    Home

A Beginner's Guide to heatmap in Pyplot

Heatmap represents individual values of data in different colors. Sing heat map, we can clearly understand which areas have high values and which areas have low values.

 

For example, consider following companies sales data.

 

Company

Jan

Feb

Mar

A

1000

1100

1900

B

1500

1200

1400

C

1200

1100

800

 

 Above snippet generates below heat map.

 


 

Using the above figure, we can clearly identifies the yellow color box has the maximum value.

 

Find the below working application.

 

hello_world.py

import matplotlib.pyplot as plt
import pandas as pd

import pandas as pd

# Sample data
data = {
    'Company': ['A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C'],
    'Month': ['Jan', 'Jan', 'Jan', 'Feb', 'Feb', 'Feb', 'Mar', 'Mar', 'Mar'],
    'Sales': [1000, 1500, 1200, 1100, 1200, 1100, 1900, 1400, 800]
}

# Create a DataFrame
df = pd.DataFrame(data)

# Pivot the data for heatmap
heatmap_data = df.pivot(index='Company', columns='Month', values='Sales')

# Create a heatmap using imshow
plt.imshow(heatmap_data, cmap='viridis', interpolation='nearest')

# Add color bar for reference
plt.colorbar()

# Add labels and title
plt.xticks(range(len(heatmap_data.columns)), heatmap_data.columns)
plt.yticks(range(len(heatmap_data.index)), heatmap_data.index)
plt.xlabel('Month')
plt.ylabel('Company')
plt.title('Sales Heatmap')

# Display the heatmap
plt.show()

In this code, I created the sales data and created a dataframe ‘df’ from it. Then, I used the pivot() function to reshape the data into a suitable format for a heatmap.

 

Month     Feb   Jan   Mar

Company                 

A        1100  1000  1900

B        1200  1500  1400

C        1100  1200   800

 

The resulting heatmap_data DataFrame contains sales values as rows (companies) and columns (months).

 

Finally I used pyplot.imshow() method to create the heatmap, specifying the 'viridis' colormap and interpolation method.

 

‘plt.colorbar()’ method adds a color bar for reference.

 

Add values in the heatmap cells

Using text annotations to the heatmap, we can display the actual values in the cells of the heatmap.

 

Example

# Add text annotations to display values
for i in range(len(heatmap_data)):
    for j in range(len(heatmap_data.columns)):
        plt.text(j, i, heatmap_data.iloc[i, j], ha='center', va='center', color='black')

Find the below working application.

 

add_values_in_heatmap.py

import matplotlib.pyplot as plt
import pandas as pd

import pandas as pd

# Sample data
data = {
    'Company': ['A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C'],
    'Month': ['Jan', 'Jan', 'Jan', 'Feb', 'Feb', 'Feb', 'Mar', 'Mar', 'Mar'],
    'Sales': [1000, 1500, 1200, 1100, 1200, 1100, 1900, 1400, 800]
}

# Create a DataFrame
df = pd.DataFrame(data)

# Pivot the data for heatmap
heatmap_data = df.pivot(index='Company', columns='Month', values='Sales')
print(heatmap_data)

# Create a heatmap using imshow
plt.imshow(heatmap_data, cmap='viridis', interpolation='nearest')

# Add color bar for reference
plt.colorbar()

# Add text annotations to display values
for i in range(len(heatmap_data)):
    for j in range(len(heatmap_data.columns)):
        plt.text(j, i, heatmap_data.iloc[i, j], ha='center', va='center', color='black')


# Add labels and title
plt.xticks(range(len(heatmap_data.columns)), heatmap_data.columns)
plt.yticks(range(len(heatmap_data.index)), heatmap_data.index)
plt.xlabel('Month')
plt.ylabel('Company')
plt.title('Sales Heatmap')

# Display the heatmap
plt.show()

Output



As you see above image, column names are coming is alphabetical order, but I want to preserve the column names in the order like Jan, Feb and Mar etc.,

 

We can preserve columns order by creating a categorical data type for the columns you want to pivot on.

 

month_order = ['Jan', 'Feb', 'Mar']

df['Month'] = pd.Categorical(df['Month'], categories=month_order, ordered=True)

 

Find the below working application.

 

preserve_column_names.py

import matplotlib.pyplot as plt
import pandas as pd

import pandas as pd

# Sample data
data = {
    'Company': ['A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C'],
    'Month': ['Jan', 'Jan', 'Jan', 'Feb', 'Feb', 'Feb', 'Mar', 'Mar', 'Mar'],
    'Sales': [1000, 1500, 1200, 1100, 1200, 1100, 1900, 1400, 800]
}

# Create a DataFrame
df = pd.DataFrame(data)

month_order = ['Jan', 'Feb', 'Mar']
df['Month'] = pd.Categorical(df['Month'], categories=month_order, ordered=True)

# Pivot the data for heatmap
heatmap_data = df.pivot(index='Company', columns='Month', values='Sales')
print(heatmap_data)

# Create a heatmap using imshow
plt.imshow(heatmap_data, cmap='viridis', interpolation='nearest')

# Add color bar for reference
plt.colorbar()

# Add text annotations to display values
for i in range(len(heatmap_data)):
    for j in range(len(heatmap_data.columns)):
        plt.text(j, i, heatmap_data.iloc[i, j], ha='center', va='center', color='black')


# Add labels and title
plt.xticks(range(len(heatmap_data.columns)), heatmap_data.columns)
plt.yticks(range(len(heatmap_data.index)), heatmap_data.index)
plt.xlabel('Month')
plt.ylabel('Company')
plt.title('Sales Heatmap')

# Display the heatmap
plt.show()

Output

 


Customize cell colors using a custom color map

We can customize the colors of heatmap cells, either by a built-in color map or using matplotlib.colors.LinearSegmentedColormap.

 

Using built-in color map 'coolwarm'

custom_colormap = plt.cm.get_cmap('coolwarm')

plt.imshow(heatmap_data, cmap=custom_colormap, interpolation='nearest')

 

customize-using-built-in-color-map.py

import matplotlib.pyplot as plt
import pandas as pd

import pandas as pd

# Sample data
data = {
    'Company': ['A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C'],
    'Month': ['Jan', 'Jan', 'Jan', 'Feb', 'Feb', 'Feb', 'Mar', 'Mar', 'Mar'],
    'Sales': [1000, 1500, 1200, 1100, 1200, 1100, 1900, 1400, 800]
}

# Create a DataFrame
df = pd.DataFrame(data)

month_order = ['Jan', 'Feb', 'Mar']
df['Month'] = pd.Categorical(df['Month'], categories=month_order, ordered=True)

# Pivot the data for heatmap
heatmap_data = df.pivot(index='Company', columns='Month', values='Sales')
print(heatmap_data)

custom_colormap = plt.cm.get_cmap('coolwarm')

# Create a heatmap using imshow
plt.imshow(heatmap_data, cmap=custom_colormap, interpolation='nearest')

# Add color bar for reference
plt.colorbar()

# Add text annotations to display values
for i in range(len(heatmap_data)):
    for j in range(len(heatmap_data.columns)):
        plt.text(j, i, heatmap_data.iloc[i, j], ha='center', va='center', color='black')

# Add labels and title
plt.xticks(range(len(heatmap_data.columns)), heatmap_data.columns)
plt.yticks(range(len(heatmap_data.index)), heatmap_data.index)
plt.xlabel('Month')
plt.ylabel('Company')
plt.title('Sales Heatmap')

# Display the heatmap
plt.show()

 Output


 

 

We can even customize the colormap range using  vmin and vmax parameters, these allows to emphasize specific ranges of values.

 

Example

custom_colormap = plt.cm.get_cmap('coolwarm')

plt.imshow(data, cmap=custom_colormap, vmin=0.2, vmax=0.8)

 

specify_colormap_range.py

import matplotlib.pyplot as plt
import numpy as np

data = np.random.random((5, 5))

custom_colormap = plt.cm.get_cmap('coolwarm')
plt.imshow(data, cmap=custom_colormap, vmin=0.2, vmax=0.8)

plt.colorbar()
plt.title('Modified Colormap Range')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')

plt.show()

Output



colormaps like 'coolwarm', 'RdBu', or 'seismic'  are used highlight positive and negative values differently.

 

Create custom color map using LinearSegmentedColormap

# Define custom colors and their positions in the colormap
custom_colors = [(0, 'white'), (0.2, 'purple'), (0.4, 'blue'), (0.6, 'green'), (1, 'yellow')]
custom_colormap = mcolors.LinearSegmentedColormap.from_list('custom', custom_colors)

# Create a heatmap using imshow
plt.imshow(heatmap_data, cmap=custom_colormap, interpolation='nearest')

Find the below working application.

 

custom_color_map.py

import matplotlib.pyplot as plt
import matplotlib.colors as mcolors

import pandas as pd

# Sample data
data = {
    'Company': ['A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C'],
    'Month': ['Jan', 'Jan', 'Jan', 'Feb', 'Feb', 'Feb', 'Mar', 'Mar', 'Mar'],
    'Sales': [1000, 1500, 1200, 1100, 1200, 1100, 1900, 1400, 800]
}

# Create a DataFrame
df = pd.DataFrame(data)

month_order = ['Jan', 'Feb', 'Mar']
df['Month'] = pd.Categorical(df['Month'], categories=month_order, ordered=True)

# Pivot the data for heatmap
heatmap_data = df.pivot(index='Company', columns='Month', values='Sales')
print(heatmap_data)

# Define custom colors and their positions in the colormap
custom_colors = [(0, 'white'), (0.2, 'purple'), (0.4, 'blue'), (0.6, 'green'), (1, 'yellow')]
# Create a custom colormap
custom_colormap = mcolors.LinearSegmentedColormap.from_list('custom', custom_colors)

# Create a heatmap using imshow
plt.imshow(heatmap_data, cmap=custom_colormap, interpolation='nearest')

# Add color bar for reference
plt.colorbar()

# Add text annotations to display values
for i in range(len(heatmap_data)):
    for j in range(len(heatmap_data.columns)):
        plt.text(j, i, heatmap_data.iloc[i, j], ha='center', va='center', color='black')

# Add labels and title
plt.xticks(range(len(heatmap_data.columns)), heatmap_data.columns)
plt.yticks(range(len(heatmap_data.index)), heatmap_data.index)
plt.xlabel('Month')
plt.ylabel('Company')
plt.title('Sales Heatmap')

# Display the heatmap
plt.show()

Output




Previous                                                    Next                                                    Home