Histograms plot
Histograms are a fundamental tool in data visualization, providing a graphical representation
of the distribution of data. They are particularly useful for exploring continuous data, such
as numerical measurements or sensor readings.
It is a type of bar plot where the X-axis represents the bin ranges while the Y-axis gives
information about frequency.
The [Link]() function is used to compute and create a histogram
Create a Basic Histogram in Matplotlib
import [Link] as plt
import numpy as np
# Generate random data for the histogram
data = [Link](1000)
# Plotting a basic histogram
[Link](data, bins=30, color='skyblue', edgecolor='black')
# Adding labels and title
[Link]('Values')
[Link]('Frequency')
[Link]('Basic Histogram')
# Display the plot
[Link]()
Customized Histogram in Matplotlib with Density Plot
Let’s create a customized histogram with a density plot using Matplotlib and Seaborn in
Python. The resulting plot visualizes the distribution of random data with a smooth density
estimate.
import [Link] as plt
import seaborn as sns
import numpy as np
# Generate random data for the histogram
data = [Link](1000)
# Creating a customized histogram with a density plot
[Link](data, bins=30, kde=True, color='lightgreen', edgecolor='red')
# Adding labels and title
[Link]('Values')
[Link]('Density')
[Link]('Customized Histogram with Density Plot')
# Display the plot
[Link]()
Output:
Multiple Histograms with Subplots
Let’s generates two histograms side by side using Matplotlib in Python, each with its own
set of random data and provides a visual comparison of the distributions
of data1 and data2 using histograms.
import [Link] as plt
import numpy as np
# Generate random data for multiple histograms
data1 = [Link](1000)
data2 = [Link](loc=3, scale=1, size=1000)
# Creating subplots with multiple histograms
fig, axes = [Link](nrows=1, ncols=2, figsize=(12, 4))
axes[0].hist(data1, bins=30, color='Yellow', edgecolor='black')
axes[0].set_title('Histogram 1')
axes[1].hist(data2, bins=30, color='Pink', edgecolor='black')
axes[1].set_title('Histogram 2')
# Adding labels and title
for ax in axes:
ax.set_xlabel('Values')
ax.set_ylabel('Frequency')
# Adjusting layout for better spacing
plt.tight_layout()
# Display the figure
[Link]()
Output:
Stacked Histogram using Matplotlib
Let’s generates a stacked histogram using Matplotlib in Python, representing two datasets
with different random data distributions. The stacked histogram provides insights into the
combined frequency distribution of the two datasets.
import [Link] as plt
import numpy as np
# Generate random data for stacked histograms
data1 = [Link](1000)
data2 = [Link](loc=3, scale=1, size=1000)
# Creating a stacked histogram
[Link]([data1, data2], bins=30, stacked=True, color=['cyan', 'Purple'],
edgecolor='black')
# Adding labels and title
[Link]('Values')
[Link]('Frequency')
[Link]('Stacked Histogram')
# Adding legend
[Link](['Dataset 1', 'Dataset 2'])
# Display the plot
[Link]()
Output:
Plot 2D Histogram (Hexbin Plot) using Matplotlib
Let’s generates a 2D hexbin plot using Matplotlib in Python, provides a visual representation
of the 2D data distribution, where hexagons convey the density of data points. The colorbar
helps interpret the density of points in different regions of the plot.
import [Link] as plt
import numpy as np
# Generate random 2D data for hexbin plot
x = [Link](1000)
y = 2 * x + [Link](size=1000)
# Creating a 2D histogram (hexbin plot)
[Link](x, y, gridsize=30, cmap='Blues')
# Adding labels and title
[Link]('X values')
[Link]('Y values')
[Link]('2D Histogram (Hexbin Plot)')
# Adding colorbar
[Link]()
# Display the plot
[Link]()
Output:
Three-dimensional Plotting in Python using Matplotlib
3D plots are very important tools for visualizing data that have three dimensions such as data
that have two dependent and one independent variable.
By plotting data in 3d plots we can get a deeper understanding of data that have three variables.
We can use various matplotlib library functions to plot 3D plots.
Example Of Three-dimensional Plotting using Matplotlib
We will first start with plotting the 3D axis using the Matplotlib library. For plotting the 3D
axis we just have to change the projection parameter of [Link]() from None to 3D.
import numpy as np
import [Link] as plt
fig = [Link]()
ax = [Link](projection='3d')
Output:
With the above syntax three -dimensional axes are enabled and data can be plotted in 3
dimensions. 3 dimension graph gives a dynamic approach and makes data more interactive.
Like 2-D graphs, we can use different ways to represent to plot 3-D graphs. We can make a
scatter plot, contour plot, surface plot, etc.
Let’s have a look at different 3-D plots.
Graphs with lines and points are the simplest 3-dimensional graph. We will use ax.plot3d
and [Link] functions to plot line and point graph respectively.
3-Dimensional Line Graph Using Matplotlib
For plotting the 3-Dimensional line graph we will use the mplot3d function from the
mpl_toolkits library. For plotting lines in 3D we will have to initialize three variable points for
the line equation. In our case, we will define three variables as x, y, and z.
# importing mplot3d toolkits, numpy and matplotlib
from mpl_toolkits import mplot3d
import numpy as np
import [Link] as plt
fig = [Link]()
# syntax for 3-D projection
ax = [Link](projection ='3d')
# defining all 3 axis
z = [Link](0, 1, 100)
x = z * [Link](25 * z)
y = z * [Link](25 * z)
# plotting
ax.plot3D(x, y, z, 'green')
ax.set_title('3D line plot geeks for geeks')
[Link]()
Output:
3-Dimensional Scattered Graph Using Matplotlib
To plot the same graph using scatter points we will use the scatter() function from matplotlib.
It will plot the same line equation using distinct points.
# importing mplot3d toolkits
from mpl_toolkits import mplot3d
import numpy as np
import [Link] as plt
fig = [Link]()
# syntax for 3-D projection
ax = [Link](projection ='3d')
# defining axes
z = [Link](0, 1, 100)
x = z * [Link](25 * z)
y = z * [Link](25 * z)
c=x+y
[Link](x, y, z, c = c)
# syntax for plotting
ax.set_title('3d Scatter plot geeks for geeks')
[Link]()
Output:
Surface Graphs using Matplotlib library
Surface graphs and Wireframes graph work on gridded data. They take the grid value and plot
it on a three-dimensional surface. We will use the plot_surface() function to plot the surface
plot.
Python3
# importing libraries
from mpl_toolkits import mplot3d
import numpy as np
import [Link] as plt
# defining surface and axes
x = [Link]([Link](-2, 2, 10), [Link](10))
y = [Link]().T
z = [Link](x ** 2 + y ** 3)
fig = [Link]()
# syntax for 3-D plotting
ax = [Link](projection='3d')
# syntax for plotting
ax.plot_surface(x, y, z, cmap='viridis',\
edgecolor='green')
ax.set_title('Surface plot geeks for geeks')
[Link]()
Output:
Surface plot using matplotlib library
Wireframes graph using Matplotlib library
For plotting the wireframes graph we will use the plot_wireframe() function from the
matplotlib library.
Python3
from mpl_toolkits import mplot3d
import numpy as np
import [Link] as plt
# function for z axis
def f(x, y):
return [Link]([Link](x ** 2 + y ** 2))
# x and y axis
x = [Link](-1, 5, 10)
y = [Link](-1, 5, 10)
X, Y = [Link](x, y)
Z = f(X, Y)
fig = [Link]()
ax = [Link](projection ='3d')
ax.plot_wireframe(X, Y, Z, color ='green')
ax.set_title('wireframe geeks for geeks');
Output:
Basemap
What is Basemap?
The Matplotlib Basemap toolkit is an extension to Matplotlib that provides functionality for
creating maps and visualizations involving geographical data.
It allows users to plot data on various map projections, draw coastlines, countries and other
map features .
Map Projections
Basemap supports various map projections by allowing users to visualize data in different
coordinate systems like cylindrical, conic or azimuthal projections. Examples are Mercator,
Lambert Conformal Conic and Orthographic projections.
Plotting Geographic Data
Basemap allows the plotting of geographical data such as points, lines, or polygons over maps.
Users can overlay datasets onto maps and visualize geographic relationships.
Map Elements
Basemap provides functions to add map elements like coastlines, countries, states, rivers and
political boundaries by enhancing the visual context of the maps.
Coordinate Transformation
It facilitates seamless conversion between different coordinate systems such as latitude and
longitude to map projection coordinates and vice versa.
Installing Basemap
If we want to work with Basemap of matplotlib library we have to install it in our working
environment. The below is the code.
Example
pip install basemap
Basic Workflow with Basemap
The below is the basic workflow of the Basemap of the Matplotlib library. Let’s see each of
them in detail for better understanding.
Create a Basemap Instance
Instantiate a Basemap object by specifying the map projection, bounding coordinates and other
parameters. To create a Basemap instance using the Basemap toolkit in Matplotlib we can
define the map projection and specify the desired map boundaries.
Example
In this example we are generating a basic map with coastlines and country boundaries using
the specified Mercator projection and the provided bounding coordinates. We can further
customize the map by adding features, plotting data points or using different projections and
resolutions based on our requirements.
from mpl_toolkits.basemap import Basemap
import [Link] as plt
# Create a Basemap instance with a specific projection and bounding coordinates
map = Basemap(
projection='merc', llcrnrlat=-80, urcrnrlat=80,
llcrnrlon=-180, urcrnrlon=180, resolution='c')
# Draw coastlines and countries
[Link]()
[Link]()
# Show the map
[Link]()
Output
Plot Data on the Map
In this we use the Basemap methods to draw map features, plot data points or visualize
geographical datasets.
Example
In this example we are generating random latitude and longitude points and then uses
the map() function to project these coordinates onto the Basemap instance.
The scatter() method is then used to plot these projected points on the map as red markers.
from mpl_toolkits.basemap import Basemap
import [Link] as plt
import numpy as np
# Create a Basemap instance with a specific projection and bounding coordinates
map = Basemap(
projection='merc', llcrnrlat=-80, urcrnrlat=80,
llcrnrlon=-180, urcrnrlon=180, resolution='c')
# Draw coastlines and countries
[Link]()
[Link]()
# Generate random data (longitude, latitude) for plotting
num_points = 100
lons = [Link](low=-180.0, high=180.0, size=num_points)
lats = [Link](low=-80.0, high=80.0, size=num_points)
# Plot the data points on the map
x, y = map(lons, lats) # Project the latitudes and longitudes to map coordinates
[Link](x, y, marker='o', color='red', zorder=10) # Plotting the data points
# Show the map with plotted data
[Link]('Data Points on Map')
[Link]()
Output
Display the Map
We can use Matplotlib library to show() function to display the final map.
Example
Here's an example demonstrating the usage of Basemap to create a map and plot data points.
from mpl_toolkits.basemap import Basemap
import [Link] as plt
import numpy as np
# Creating a Basemap instance with a specific projection and bounding coordinates
map = Basemap(
projection='merc', llcrnrlat=-80, urcrnrlat=80,
llcrnrlon=-180, urcrnrlon=180, resolution='c')
# Drawing coastlines, countries, and states
[Link]()
[Link]()
[Link]()
# Generating random data for plotting
num_points = 100
lons = [Link](low=-180.0, high=180.0, size=num_points)
lats = [Link](low=-80.0, high=80.0, size=num_points)
data_values = [Link](num_points) * 100 # Random values for data
# Plotting data points on the map
x, y = map(lons, lats) # Projecting latitudes and longitudes to map coordinates
[Link](x, y, c=data_values, cmap='viridis', marker='o', alpha=0.7)
# Adding a colorbar to represent the data values
[Link](label='Data Values')
# Display the map with plotted data
[Link]('Basemap Example with Data Points')
[Link]()
Output
Applications of Matplotlib Basemap
Geospatial Analysis − Analyzing and visualizing geographical data such as climate patterns,
population distributions or seismic activities.
Cartography − Creating custom maps for publications, presentations or research purposes.
Data Visualization − Integrating geographical data with other datasets for exploratory data
analysis.
Visualization with Seaborn.
Seaborn is a Python data visualization library based on Matplotlib, designed to make it easier
to create informative and attractive statistical graphics. It provides a high-level interface for
drawing a wide variety of plots that are useful for exploring datasets.
Key Features of Seaborn:
Built-in themes for better looking visualizations.
Works well with Pandas DataFrames to easily plot data.
Provides functions for statistical plots, like regression plots, distribution plots, etc.
Easily handles complex visualizations involving categorical data.
How to Use Seaborn for Visualization
1. Importing Seaborn
First, you need to install and import Seaborn.
pip install seaborn
import seaborn as sns
import [Link] as plt
2. Basic Plot Types in Seaborn
a. Scatter Plot ([Link])
A scatter plot is used to plot individual data points based on two continuous variables.
# Load an example dataset
tips = sns.load_dataset("tips")
# Scatter plot of total_bill vs tip
[Link](x='total_bill', y='tip', data=tips)
[Link]()
b. Line Plot ([Link])
Line plots are useful for showing trends over a period of time.
# Line plot of total_bill vs tip
[Link](x='total_bill', y='tip', data=tips)
[Link]()
c. Histogram and KDE Plot ([Link] and [Link])
Histograms and kernel density estimate (KDE) plots are used to visualize the distribution of a
variable.
# Histogram for 'total_bill' column
[Link](tips['total_bill'], bins=20)
[Link]()
# KDE plot for 'total_bill'
[Link](tips['total_bill'], shade=True)
[Link]()
d. Bar Plot ([Link])
Bar plots are used to show the relationship between a categorical variable and a continuous
variable.
# Bar plot of average tip by day
[Link](x='day', y='tip', data=tips)
[Link]()
e. Box Plot ([Link])
Box plots show the distribution of quantitative data and help to identify outliers.
# Box plot of total_bill by day
[Link](x='day', y='total_bill', data=tips)
[Link]()
f. Violin Plot ([Link])
Violin plots are similar to box plots but also show the kernel density estimation.
# Violin plot of total_bill by day
[Link](x='day', y='total_bill', data=tips)
[Link]()
g. Heatmap ([Link])
Heatmaps are used for visualizing matrices or showing correlations between variables.
# Correlation heatmap
corr = [Link]()
[Link](corr, annot=True, cmap='coolwarm')
[Link]()
3. Advanced Plots
a. Pair Plot ([Link])
Pair plots show the relationships between all pairs of variables in a dataset, often used for
exploratory data analysis.
# Pair plot of numerical columns
[Link](tips)
[Link]()
b. FacetGrid
FacetGrid is useful for plotting subsets of data across multiple subplots.
# FacetGrid for plotting total_bill distribution for each day
g = [Link](tips, col="day")
[Link]([Link], "total_bill")
[Link]()
c. Joint Plot ([Link])
A joint plot shows the relationship between two variables and the distribution of each
variable on the sides.
# Joint plot of total_bill vs tip
[Link](x='total_bill', y='tip', data=tips, kind="hex")
[Link]()
4. Customization in Seaborn
Seaborn offers customization options to improve the appearance of plots. You can change
styles, color palettes, and more.
a. Changing Style
You can set the style of the plot to different themes like darkgrid, whitegrid, dark, white, and
ticks.
sns.set_style("darkgrid")
[Link](x='day', y='total_bill', data=tips)
[Link]()
b. Color Palettes
Seaborn provides different color palettes to enhance the aesthetics of your plots.
sns.set_palette("Set2")
[Link](x='day', y='tip', data=tips)
[Link]()
c. Adding Titles and Labels
You can add titles, labels, and adjust plot elements for clarity.
[Link](x='total_bill', y='tip', data=tips)
[Link]('Scatter Plot of Total Bill vs Tip')
[Link]('Total Bill')
[Link]('Tip')
[Link]()
5. Combining Seaborn with Matplotlib
Since Seaborn is built on top of Matplotlib, you can use Matplotlib functions to further
customize your Seaborn plots.
[Link](x='day', y='total_bill', data=tips)
[Link]('Bar Plot of Total Bill by Day')
[Link]('Day of the Week')
[Link]('Total Bill')
[Link](True)
[Link]()