0% found this document useful (0 votes)
2 views17 pages

Errorbar Graph in Python Using Matplotlib

The document provides an overview of error bar graphs, density plots, and contour plots in Python using Matplotlib. It explains how to visualize data variability with error bars, create density plots to analyze distributions, and generate contour plots for 3-D surface visualization. Several examples with code snippets illustrate the implementation of these plotting techniques.

Uploaded by

vaishalisri3105
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)
2 views17 pages

Errorbar Graph in Python Using Matplotlib

The document provides an overview of error bar graphs, density plots, and contour plots in Python using Matplotlib. It explains how to visualize data variability with error bars, create density plots to analyze distributions, and generate contour plots for 3-D surface visualization. Several examples with code snippets illustrate the implementation of these plotting techniques.

Uploaded by

vaishalisri3105
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

Errorbar graph in Python using Matplotlib

Error bars function used as graphical enhancement that visualizes the variability of the plotted
data on a Cartesian graph. Error bars can be applied to graphs to provide an additional layer of
detail on the presented data. As you can see in below graphs.

Error bars help you indicate estimated error or uncertainty to give a general sense of how
precise a measurement is this is done through the use of markers drawn over the original graph
and its data points.
To visualize this information error bars work by drawing lines that extend from the center of
the plotted data point or edge with bar charts the length of an error bar helps to reveal
uncertainty of a data point as shown in the below graph. A short error bar shows that values
are concentrated signaling that the plotted averaged value is more likely while a long error bar
would indicate that the values are more spread out and less reliable. also depending on the type
of data. the length of each pair of error bars tends to be of equal length on both sides, however,
if the data is skewed then the lengths on each side would be unbalanced.

Error bars always run parallel to a quantity of scale axis so they can be displayed either
vertically or horizontally depending on whether the quantitative scale is on the y-axis or x-axis
if there are two quantity of scales and two pairs of arrow bars can be used for both axes.

Let see an example of errorbar how it works.


Creating a Simple Graph.

# importing matplotlib
import [Link] as plt
# making a simple plot
x =[1, 2, 3, 4, 5, 6, 7]
y =[1, 2, 1, 2, 1, 2, 1]

# plotting graph
[Link](x, y)

Output:

Example 1: Adding Some error in y value.

# importing matplotlib
import [Link] as plt

# making a simple plot


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

# creating error
y_error = 0.2
# plotting graph
[Link](x, y)

[Link](x, y,
yerr = y_error,
fmt ='o')

Output:

Example 2: Adding Some error in x value.

 Python3

# importing matplotlib
import [Link] as plt

# making a simple plot


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

# creating error
x_error = 0.5

# plotting graph
[Link](x, y)
[Link](x, y,
xerr = x_error,
fmt ='o')

Output:

Example 3: Adding error in x & y

# importing matplotlib
import [Link] as plt

# making a simple plot


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

# creating error
x_error = 0.5
y_error = 0.3

# plotting graph
[Link](x, y)
[Link](x, y,
yerr = y_error,
xerr = x_error,
fmt ='o')

Output:

Example 4: Adding variable error in x and y

# importing matplotlib
import [Link] as plt

# making a simple plot


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

# creating error
y_errormin =[0.1, 0.5, 0.9,
0.1, 0.9]
y_errormax =[0.2, 0.4, 0.6,
0.4, 0.2]
x_error = 0.5
y_error =[y_errormin, y_errormax]

# plotting graph
# [Link](x, y)
[Link](x, y,
yerr = y_error,
xerr = x_error,
fmt ='o')

Output:

Example 5:

 Python3

# import require modules


import numpy as np
import [Link] as plt

# defining our function


x = [Link](10)/10
y = (x + 0.1)**2
# defining our error
y_error = [Link](0.05, 0.2, 10)

# plotting our function and


# error bar
[Link](x, y)

[Link](x, y, yerr = y_error, fmt ='o')

Output:
Density Plots in Python
Density Plot is a type of data visualization tool. It is a variation of the histogram
that uses ‘kernel smoothing’ while plotting the values. It is a continuous and
smooth version of a histogram inferred from a data.
Density plots uses Kernel Density Estimation (so they are also known as Kernel
density estimation plots or KDE) which is a probability density function. The
region of plot with a higher peak is the region with maximum data points residing
between those values.
Density plots can be made using pandas, seaborn, etc.
We will be using two datasets of the Seaborn Library namely – ‘car_crashes’ and
‘tips’.
Syntax: [Link] | [Link]

where pandas -> the dataset of the type ‘pandas dataframe’


Dataframe -> the column for which the density plot is to be drawn
plot -> keyword directing to draw a plot/graph for the given column
density -> for plotting a density graph
kde -> to plot a density graph using the Kernel Density Estimation function

Example 1: Given the dataset ‘car_crashes’, let’s find out using the density plot
which is the most common speed due to which most of the car crashes happened.
Python3

# importing the libraries


import pandas as pd
import seaborn as sns
import [Link] as plt

# loading the dataset


# from seaborn library
data = sns.load_dataset('car_crashes')

# viewing the dataset


print([Link](4))
Output:
Plotting the graph:

# plotting the density plot


# for 'speeding' attribute
# using [Link]()
[Link](color='green')
[Link]('Density plot for Speeding')
[Link]()

Output:

Using a density plot, we can figure out that the speed between 4-5 (kmph) was
the most common for crash crashes in the dataset because of it being high density
(high peak) region.
Example 2: For another dataset ‘tips’, let’s calculate what was the most common
tip given by a customer.

# loading the dataset


# from seaborn library
data = sns.load_dataset('tips')

# viewing the dataset


print([Link](4))

Output:

‘tips’ dataset

# density plot for 'tip'


[Link](color='green')
[Link]('Density Plot for Tip')
[Link]()

Through the above density plot, we can infer that the most common tip that was
given was in the range of 2.5 – 3. The highest peak/density (as represented on the
y-axis) was found to be at the tip value of 2.5 – 3.
Plotting the above plot using the [Link]()
KDE or the Kernel Density Estimation uses Gaussian Kernels to estimate the
Probability Density Function of a random variable. Below is the implementation
of plotting the density plot using kde() for the dataset ‘tips’.

# for 'tip' attribute


# using [Link]()
[Link](color='green')
[Link]('KDE-Density plot for Tip')
[Link]()

Using this we can infer that there is no major difference between [Link]()
and [Link]() and can be therefore used interchangeably.
Density plots have an advantage over Histograms because they determine the
Shape of the distribution more efficiently than histograms. They do not have to
depend on the number of bins used unlike in histograms.

Contour plots

A contour plot is a graphical method to visualize the 3-D surface by plotting


constant Z slices called contours in a 2-D format. The contour plot is an
alternative to a 3-D surface plot

The contour plot is formed by:

 Vertical axis: Independent variable 2


 Horizontal axis: Independent variable 1
 Lines: iso-response values, can be calculated with the help (x,y).
The independent variable usually restricted to a regular grid. The actual
techniques for determining the correct iso-response values are rather complex and
almost always computer-generated.
The contour plot is used to depict the change in Z values as compared to X and
Y values. If the data (or function) do not form a regular grid, you typically need
to perform a 2-D interpolation to form a regular grid.

For one variable data, a run sequence/ histogram is considered necessary. For
two-variable data, a scatter plot is considered necessary. The contour plots can
also polar co-ordinates (r,theta) instead of traditional rectangular (x, y, z)
coordinates.

Types of Contour Plot:


 Rectangular Contour plot: A projection of 2D-plot in 2D-rectangular
canvas. It is the most common form of the contour plot.
 Polar contour plot: Polar contour plot is plotted by using the polar
coordinates r and theta. The response variable here is the collection of values
generated while passing r and theta into the given function, where r is the
distance from origin and theta is the angle from the positive x axis.
 Ternary contour plot: Ternary contour plot is used to represent the
relationship between 3 explanatory variables and the response variable in the
form of a filled triangle.
Contour plot can be plotted in different programming languages:

 Python/ Matplotlib: Contour plot can be plotted


using [Link] or [Link] functions, where plt is [Link].
The difference between these two that [Link] generates hollow contour
plot, the [Link] generated filled.
 Matlab: functions such as contourf (2d-plot) and contour3 (3D-contour) can
be used for contour plotting
 R: can create a contour plot with [Link] functions in R.
Implementations:
 Rectangular Contour Plot: Below is the sample code for plotting rectangular
contour plots in Python and matplotlib.

# imports
import numpy as np
import [Link] as plt
#
# define a function
def func(x, y):
return [Link](x) ** 2 + [Link](y) **2
# generate 50 values b/w 0 a5
x = [Link](0, 5, 50)
y = [Link](0, 5, 50)

# Generate combination of grids


X, Y = [Link](x, y)
Z = func(X, Y)

# Draw rectangular contour plot


[Link](X, Y, Z, cmap='gist_rainbow_r');
[Link]()
 Polar Contour plot: For plotting polar contour plot we need to define first r
and theta. Below is the sample code for plotting polar contour plots using
matplotlib subplots.

# generate r and theta arrays


rad_arr = [Link]([Link](0, 360, 20))
r_arr = [Link](0, 1, .1)
# define function
def func(r, theta):
return r * [Link](theta)

r, theta = [Link](r_arr, rad_arr)


# get the values of response variables
values = func(r,theta)

# plot the polar coordinates


fig, ax = [Link](subplot_kw=dict(projection='polar'))
[Link](theta, r, values, cmap='Spectral_r')

[Link]()

Polar contour plot


 Ternary Contour Plot: Matplotlib does not provide a definitive API for
plotting Ternary Contour plot, however, there are many other package which
does that. IN this example, we will be using Plotly library.

# install & import plotly


! pip install plotly
import plotly.figure_factory as ff

# Define variables
a = [Link]([0. , 0. , 0., 0., 1./3, 1./3, 1./3, 2./3, 2./3, 1.])
b = [Link]([0., 1./3, 2./3, 1., 0., 1./3, 2./3, 0., 1./3, 0.])
c=1-a-b
# Define function that generates response variable
func = (a - 0.02) * b * (a - 0.5) * (b - 0.4) * (c - 1)**2

# plot ternary contour


fig = ff.create_ternary_contour([Link]([a, b, c]), func,
pole_labels=['a', 'b', 'c'],
interp_mode='cartesian',
colorscale='Viridis',)
[Link]()
Ternary Contour plot

You might also like