IDS U-5
IDS U-5
Matplotlib:
Installation of Matplotlib
If you have Python and PIP already installed on a system, then installation of
Matplotlib is very easy.
If this command fails, then use a python distribution that already has Matplotlib
installed, like Anaconda, Spyder etc.
Import Matplotlib
Once Matplotlib is installed, import it in your applications by adding
the import module statement:
import matplotlib
print(matplotlib.__version__)
2.0.0
Matplotlib Pyplot
Pyplot
Most of the Matplotlib utilities lies under the pyplot submodule, and are usually
imported under the plt alias:
plt.plot(xpoints, ypoints)
plt.show()
Result:
Matplotlib Plotting
Plotting x and y points
plt.plot(xpoints, ypoints)
plt.show()
Result:
To plot only the markers, you can use shortcut string notation parameter 'o', which
means 'rings'.
Example
Draw two points in the diagram, one at position (1, 3) and one in position (8, 10):
Multiple Points
You can plot as many points as you like, just make sure you have the same number
of points in both axis.
Example
Draw a line in a diagram from position (1, 3) to (2, 8) then to (6, 1) and finally to
position (8, 10):
import matplotlib.pyplot as plt
import numpy as np
plt.plot(xpoints, ypoints)
plt.show()
Result:
Default X-Points
If we do not specify the points on the x-axis, they will get the default values 0, 1, 2,
3 etc., depending on the length of the y-points.
So, if we take the same example as above, and leave out the x-points, the diagram
will look like this:
Example
plt.plot(ypoints)
plt.show()
Result:
Matplotlib Markers
Markers
You can use the keyword argument marker to emphasize each point with a
specified marker:
Example
...
plt.plot(ypoints, marker = '*')
...
Result:
Result:
You can also use the shortcut string notation parameter to specify the marker.
This parameter is also called fmt, and is written with this syntax:
marker|line|color
Example
plt.plot(ypoints, 'o:r')
plt.show()
Result:
The marker value can be anything from the Marker Reference above.
Line Reference
Note: If you leave out the line value in the fmt parameter, no line will be plotted.
import matplotlib
matplotlib.use('Agg')
import numpy as np
plt.plot(ypoints, 'or')
plt.show()
plt.savefig(sys.stdout.buffer)
sys.stdout.flush()
RESULT:
Marker Size
You can use the keyword argument markersize or the shorter version, ms to set the
size of the markers:
Example
Result:
Try it Yourself »
Marker Color
You can use the keyword argument markeredgecolor or the shorter mec to set the
color of the edge of the markers:
Example
Result:
Example
Result:
Use both the mec and mfc arguments to color the entire marker:
Example
Set the color of both the edge and the face to red:
Result:
Example
...
plt.plot(ypoints, marker = 'o', ms = 20, mec = '#4CAF50', mfc = '#4CAF50')
...
Result:
Example
...
plt.plot(ypoints, marker = 'o', ms = 20, mec = 'hotpink', mfc = 'hotpink')
...
Result:
Matplotlib Line
Linestyle
You can use the keyword argument linestyle, or shorter ls, to change the style of
the plotted line:
Result:
Try it Yourself »
Example
Result:
Shorter Syntax
Example
Shorter syntax:
plt.plot(ypoints, ls = ':')
Result:
Line Styles
Style Or
'dotted' ':'
'dashed' '--'
'dashdot' '-.'
'None'
Line Color
You can use the keyword argument color or the shorter c to set the color of the
line:
Example
Result:
Try it Yourself »
Example
...
plt.plot(ypoints, c = '#4CAF50')
...
Result:
Try it Yourself »
Example
...
plt.plot(ypoints, c = 'hotpink')
...
Result:
Line Width
You can use the keyword argument linewidth or the shorter lw to change the width
of the line.
Example
Result:
Multiple Lines
You can plot as many lines as you like by simply adding more plt.plot() functions:
Example
plt.plot(y1)
plt.plot(y2)
plt.show()
Result:
You can also plot many lines by adding the points for the x- and y-axis for each
line in the same plt.plot() function.
(In the examples above we only specified the points on the y-axis, meaning that the
points on the x-axis got the the default values (0, 1, 2, 3).)
The x- and y- values come in pairs:
Example
Draw two lines by specifiyng the x- and y-point values for both lines:
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])
Result:
Matplotlib Labels and Title
Create Labels for a Plot
With Pyplot, you can use the xlabel() and ylabel() functions to set a label for the x-
and y-axis.
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()
Result:
Create a Title for a Plot
With Pyplot, you can use the title() function to set a title for the plot.
Example
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()
Result:
Set Font Properties for Title and Labels
You can use the fontdict parameter in xlabel(), ylabel(), and title() to set font
properties for the title and labels.
Example
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])
font1 = {'family':'serif','color':'blue','size':20}
font2 = {'family':'serif','color':'darkred','size':15}
plt.plot(x, y)
plt.show()
Result:
You can use the loc parameter in title() to position the title.
Legal values are: 'left', 'right', and 'center'. Default value is 'center'.
Example
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()
Result:
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()
Result:
Try it Yourself »
ADVERTISEMENT
You can use the axis parameter in the grid() function to specify which grid lines to
display.
Legal values are: 'x', 'y', and 'both'. Default value is 'both'.
Example
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()
Result:
Try it Yourself »
Example
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.grid(axis = 'y')
plt.show()
Result:
Try it Yourself »
You can also set the line properties of the grid, like this: grid(color = 'color',
linestyle = 'linestyle', linewidth = number).
Example
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()
Result:
Matplotlib Subplot
Display Multiple Plots
With the subplot() function you can draw multiple plots in one figure:
Draw 2 plots:
#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)
#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.show()
Result:
The subplot() Function
The subplot() function takes three arguments that describes the layout of the figure.
plt.subplot(1, 2, 1)
#the figure has 1 row, 2 columns, and this plot is the first plot.
plt.subplot(1, 2, 2)
#the figure has 1 row, 2 columns, and this plot is the second plot.
So, if we want a figure with 2 rows an 1 column (meaning that the two plots will
be displayed on top of each other instead of side-by-side), we can write the syntax
like this:
Example
#plot 1:
x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])
plt.subplot(2, 1, 1)
plt.plot(x,y)
#plot 2:
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])
plt.subplot(2, 1, 2)
plt.plot(x,y)
plt.show()
Result:
You can draw as many plots you like on one figure, just descibe the number of
rows, columns, and the index of the plot.
Example
Draw 6 plots:
x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])
plt.subplot(2, 3, 1)
plt.plot(x,y)
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])
plt.subplot(2, 3, 2)
plt.plot(x,y)
x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])
plt.subplot(2, 3, 3)
plt.plot(x,y)
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])
plt.subplot(2, 3, 4)
plt.plot(x,y)
x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])
plt.subplot(2, 3, 5)
plt.plot(x,y)
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])
plt.subplot(2, 3, 6)
plt.plot(x,y)
plt.show()
Result:
ADVERTISEMENT
Title
You can add a title to each plot with the title() function:
Example
#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()
Result:
Super Title
You can add a title to the entire figure with the suptitle() function:
Example
#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.suptitle("MY SHOP")
plt.show()
Result:
Matplotlib Scatter
Creating Scatter Plots
With Pyplot, you can use the scatter() function to draw a scatter plot.
The scatter() function plots one dot for each observation. It needs two arrays of the
same length, one for the values of the x-axis, and one for values on the y-axis:
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()
Result:
The observation in the example above is the result of 13 cars passing by.
It seems that the newer the car, the faster it drives, but that could be a coincidence,
after all we only registered 13 cars.
Compare Plots
In the example above, there seems to be a relationship between speed and age, but
what if we plot the observations from another day as well? Will the scatter plot tell
us something else?
Example
plt.show()
Result:
Note: The two plots are plotted with two different colors, by default blue and
orange, you will learn how to change colors later in this chapter.
By comparing the two plots, I think it is safe to say that they both gives us the
same conclusion: the newer the car, the faster it drives.
ADVERTISEMENT
Colors
You can set your own color for each scatter plot with the color or the c argument:
Example
Set your own color of the markers:
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, color = 'hotpink')
x = np.array([2,2,8,1,15,8,12,9,7,3,11,4,7,14,12])
y = np.array([100,105,84,105,90,99,90,95,94,100,79,112,91,80,85])
plt.scatter(x, y, color = '#88c999')
plt.show()
Result:
Color Each Dot
You can even set a specific color for each dot by using an array of colors as value
for the c argument:
Note: You cannot use the color argument for this, only the c argument.
Example
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])
colors =
np.array(["red","green","blue","yellow","pink","black","orange","purple","beige","
brown","gray","cyan","magenta"])
plt.scatter(x, y, c=colors)
plt.show()
Result:
ColorMap
A colormap is like a list of colors, where each color has a value that ranges from 0
to 100.
You can specify the colormap with the keyword argument cmap with the value of
the colormap, in this case 'viridis' which is one of the built-in colormaps available
in Matplotlib.
In addition you have to create an array with values (from 0 to 100), one value for
each point in the scatter plot:
Example
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])
colors = np.array([0, 10, 20, 30, 40, 45, 50, 55, 60, 70, 80, 90, 100])
plt.show()
Result:
Example
plt.colorbar()
plt.show()
Result:
Available ColorMaps
Accent Accent_r
Blues Blues_r
BrBG BrBG_r
BuGn BuGn_r
BuPu BuPu_r
CMRmap CMRmap_r
Dark2 Dark2_r
GnBu GnBu_r
Greens Greens_r
Greys Greys_r
OrRd OrRd_r
Oranges Oranges_r
PRGn PRGn_r
Paired Paired_r
Pastel1 Pastel1_r
Pastel2 Pastel2_r
PiYG PiYG_r
Size
You can change the size of the dots with the s argument.
Just like colors, make sure the array for sizes has the same length as the arrays for
the x- and y-axis:
Example
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])
sizes = np.array([20,50,100,200,500,1000,60,90,10,300,600,800,75])
plt.scatter(x, y, s=sizes)
plt.show()
Result:
Alpha
You can adjust the transparency of the dots with the alpha argument.
Just like colors, make sure the array for sizes has the same length as the arrays for
the x- and y-axis:
Example
plt.show()
Result:
You can combine a colormap with different sizes of the dots. This is best
visualized if the dots are transparent:
Example
Create random arrays with 100 values for x-points, y-points, colors and sizes:
plt.colorbar()
plt.show()
Result:
Matplotlib Bars
Creating Bars
With Pyplot, you can use the bar() function to draw bar graphs:
ExampleGet your own Python Server
Draw 4 bars:
plt.bar(x,y)
plt.show()
Result:
The bar() function takes arguments that describes the layout of the bars.
The categories and their values represented by the first and second argument as
arrays.
Example
x = ["APPLES", "BANANAS"]
y = [400, 350]
plt.bar(x, y)
Horizontal Bars
Example
plt.barh(x, y)
plt.show()
Result:
Bar Color
The bar() and barh() take the keyword argument color to set the color of the bars:
Example
Result:
Color Names
Example
Result:
Color Hex
Example
Result:
Bar Width
The bar() takes the keyword argument width to set the width of the bars:
Example
Result:
The default width value is 0.8
Bar Height
The barh() takes the keyword argument height to set the height of the bars:
Example
Result:
Matplotlib Histograms
Histogram
Example: Say you ask for the height of 250 people, you might end up with a
histogram like this:
You can read from the histogram that there are approximately:
Create Histogram
In Matplotlib, we use the hist() function to create histograms.
The hist() function will use an array of numbers to create a histogram, the array is
sent into the function as an argument.
For simplicity we use NumPy to randomly generate an array with 250 values,
where the values will concentrate around 170, and the standard deviation is 10.
Learn more about Normal Data Distribution in our Machine Learning Tutorial.
import numpy as np
print(x)
Result:
This will generate a random result, and could look like this:
Try it Yourself »
The hist() function will read the array and produce a histogram:
Example
A simple histogram:
plt.hist(x)
plt.show()
Result:
With Pyplot, you can use the pie() function to draw pie charts:
plt.pie(y)
plt.show()
Result:
As you can see the pie chart draws one piece (called a wedge) for each value in the
array (in this case [35, 25, 25, 15]).
By default the plotting of the first wedge starts from the x-axis and
moves counterclockwise:
Note: The size of each wedge is determined by comparing the value with all the
other values, by using this formula:
Labels
Add labels to the pie chart with the label parameter.
The label parameter must be an array with one label for each wedge:
Example
Result:
Start Angle
As mentioned the default start angle is at the x-axis, but you can change the start
angle by specifying a startangle parameter.
Example
Result:
Explode
Maybe you want one of the wedges to stand out? The explode parameter allows
you to do that.
The explode parameter, if specified, and not None, must be an array with one value
for each wedge.
Each value represents how far from the center each wedge is displayed:
Example
Pull the "Apples" wedge 0.2 from the center of the pie:
Result:
Shadow
Add a shadow to the pie chart by setting the shadows parameter to True:
Example
Add a shadow:
Result:
Colors
You can set the color of each wedge with the colors parameter.
The colors parameter, if specified, must be an array with one value for each wedge:
Example
Result:
You can use Hexadecimal color values, any of the 140 supported color names, or
one of these shortcuts:
'r' - Red
'g' - Green
'b' - Blue
'c' - Cyan
'm' - Magenta
'y' - Yellow
'k' - Black
'w' - White
Legend
To add a list of explanation for each wedge, use the legend() function:
Example
Add a legend:
Result:
To add a header to the legend, add the title parameter to the legend function.
Example
Add a legend with a header:
Result:
Seaborn
Visualize Distributions With Seaborn
Seaborn is a library that uses Matplotlib underneath to plot graphs. It will be used
to visualize random distributions.
Install Seaborn.
If you have Python and PIP already installed on a system, install it using this
command:
Distplots
Distplot stands for distribution plot, it takes as input an array and plots a curve
corresponding to the distribution of points in the array.
Import Matplotlib
Import the pyplot object of the Matplotlib module in your code using the following
statement:
You can learn about the Matplotlib module in our Matplotlib Tutorial.
Import Seaborn
Import the Seaborn module in your code using the following statement:
Plotting a Distplot
ExampleGet your own Python Server
import matplotlib.pyplot as plt
import seaborn as sns
sns.distplot([0, 1, 2, 3, 4, 5])
plt.show()
Plotting a Distplot Without the Histogram
Example
import matplotlib.pyplot as plt
import seaborn as sns
plt.show()
Installation of Basemap is straightforward; if you're using conda you can type this
and the package will be downloaded:
$ conda install basemap
In [1]:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
Once you have the Basemap toolkit installed and imported, geographic plots are
just a few lines away (the graphics in the following also requires the PIL package
in Python 2, or the pillow package in Python 3):
In [2]:
plt.figure(figsize=(8, 8))
m = Basemap(projection='ortho', resolution=None, lat_0=50, lon_0=-100)
m.bluemarble(scale=0.5);
The meaning of the arguments to Basemap will be discussed momentarily.
The useful thing is that the globe shown here is not a mere image; it is a fully-
functioning Matplotlib axes that understands spherical coordinates and which
allows us to easily overplot data on the map! For example, we can use a different
map projection, zoom-in to North America and plot the location of Seattle. We'll
use an etopo image (which shows topographical features both on land and under
the ocean) as the map background:
In [3]:
fig = plt.figure(figsize=(8, 8))
m = Basemap(projection='lcc', resolution=None,
width=8E6, height=8E6,
lat_0=45, lon_0=-100,)
m.etopo(scale=0.5, alpha=0.5)
Map Projections
The first thing to decide when using maps is what projection to use. You're
probably familiar with the fact that it is impossible to project a spherical map, such
as that of the Earth, onto a flat surface without somehow distorting it or breaking
its continuity. These projections have been developed over the course of human
history, and there are a lot of choices! Depending on the intended use of the map
projection, there are certain map features (e.g., direction, area, distance, shape, or
other considerations) that are useful to maintain.
The Basemap package implements several dozen such projections, all referenced
by a short format code. Here we'll briefly demonstrate some of the more common
ones.
We'll start by defining a convenience routine to draw our world map along with the
longitude and latitude lines:
In [4]:
from itertools import chain
In [5]:
fig = plt.figure(figsize=(8, 6), edgecolor='w')
m = Basemap(projection='cyl', resolution=None,
llcrnrlat=-90, urcrnrlat=90,
llcrnrlon=-180, urcrnrlon=180, )
draw_map(m)
The additional arguments to Basemap for this view specify the latitude (lat) and
longitude (lon) of the lower-left corner (llcrnr) and upper-right corner (urcrnr) for
the desired map, in units of degrees.
Pseudo-cylindrical projections
Pseudo-cylindrical projections relax the requirement that meridians (lines of
constant longitude) remain vertical; this can give better properties near the poles of
the projection. The Mollweide projection (projection='moll') is one common
example of this, in which all meridians are elliptical arcs. It is constructed so as to
preserve area across the map: though there are distortions near the poles, the area
of small patches reflects the true area. Other pseudo-cylindrical projections are the
sinusoidal (projection='sinu') and Robinson (projection='robin') projections.
In [6]:
fig = plt.figure(figsize=(8, 6), edgecolor='w')
m = Basemap(projection='moll', resolution=None,
lat_0=0, lon_0=0)
draw_map(m)
The extra arguments to Basemap here refer to the central latitude (lat_0) and
longitude (lon_0) for the desired map.
Perspective projections
In [7]:
fig = plt.figure(figsize=(8, 8))
m = Basemap(projection='ortho', resolution=None,
lat_0=50, lon_0=0)
draw_map(m);
Conic projections
A Conic projection projects the map onto a single cone, which is then unrolled.
This can lead to very good local properties, but regions far from the focus point of
the cone may become very distorted. One example of this is the Lambert
Conformal Conic projection (projection='lcc'), which we saw earlier in the map of
North America. It projects the map onto a cone arranged in such a way that two
standard parallels (specified in Basemap by lat_1 and lat_2) have well-represented
distances, with scale decreasing between them and increasing outside of them.
Other useful conic projections are the equidistant conic projection
(projection='eqdc') and the Albers equal-area projection (projection='aea'). Conic
projections, like perspective projections, tend to be good choices for representing
small to medium patches of the globe.
In [8]:
fig = plt.figure(figsize=(8, 8))
m = Basemap(projection='lcc', resolution=None,
lon_0=0, lat_0=50, lat_1=45, lat_2=55,
width=1.6E7, height=1.2E7)
draw_map(m)
Other projections
Earlier we saw the bluemarble() and shadedrelief() methods for projecting global
images on the map, as well as the drawparallels() and drawmeridians() methods for
drawing lines of constant latitude and longitude. The Basemap package contains a
range of useful functions for drawing borders of physical features like continents,
oceans, lakes, and rivers, as well as political boundaries such as countries and US
states and counties. The following are some of the available drawing functions that
you may wish to explore using IPython's help features:
Physical boundaries and bodies of water
o drawcoastlines(): Draw continental coast lines
o drawlsmask(): Draw a mask between the land and sea, for use with
projecting images on one or the other
o drawmapboundary(): Draw the map boundary, including the fill color
for oceans.
o drawrivers(): Draw rivers on the map
o fillcontinents(): Fill the continents with a given color; optionally fill
lakes with another color
Political boundaries
o drawcountries(): Draw country boundaries
o drawstates(): Draw US state boundaries
o drawcounties(): Draw US county boundaries
Map features
o drawgreatcircle(): Draw a great circle between two points
o drawparallels(): Draw lines of constant latitude
o drawmeridians(): Draw lines of constant longitude
o drawmapscale(): Draw a linear scale on the map
Whole-globe images
o bluemarble(): Project NASA's blue marble image onto the map
o shadedrelief(): Project a shaded relief image onto the map
o etopo(): Draw an etopo relief image onto the map
o warpimage(): Project a user-provided image onto the map
Notice that the low-resolution coastlines are not suitable for this level of zoom,
while high-resolution works just fine. The low level would work just fine for a
global view, however, and would be much faster than loading the high-resolution
border data for the entire globe! It might require some experimentation to find the
correct resolution parameter for a given view: the best route is to start with a fast,
low-resolution plot and increase the resolution as needed.
Line plot:
Lineplot Is the most popular plot to draw a relationship between x and y with the
possibility of several semantic groupings.
Syntax : sns.lineplot(x=None, y=None)
Parameters:
x, y: Input data variables; must be numeric. Can pass data directly or reference
columns in data.
Let’s visualize the data with a line plot and pandas:
Example 1:
Python3
# import module
import pandas
# loading csv
data = pandas.read_csv("nba.csv")
# plotting lineplot
# import module
import pandas
data = pandas.read_csv("nba.csv")
# plot
sns.lineplot(data['Age'],data['Weight'], hue
=data["Position"])
Output:
Scatter Plot:
Scatterplot Can be used with several semantic groupings which can help to
understand well in a graph against continuous/categorical data. It can draw a two-
dimensional graph.
Syntax: seaborn.scatterplot(x=None, y=None)
Parameters:
x, y: Input data variables that should be numeric.
Returns: This method returns the Axes object with the plot drawn onto it.
Let’s visualize the data with a scatter plot and pandas:
Example 1:
Python3
# import module
import seaborn
import pandas
# load csv
data = pandas.read_csv("nba.csv")
# plotting
seaborn.scatterplot(data['Age'],data['Weig
ht'])
Output:
import pandas
data = pandas.read_csv("nba.csv")
seaborn.scatterplot( data['Age'],
data['Weight'], hue =data["Position"])
Output:
Box plot:
# import module
import pandas
sns.boxplot( data['Age'] )
Output:
Example 2:
Python3
# import module
import pandas
Output:
Violin Plot:
A violin plot is similar to a boxplot. It shows several quantitative data across one
or more categorical variables such that those distributions can be compared.
# import module
import pandas
# read csv and plot
data = pandas.read_csv("nba.csv")
sns.violinplot(data['Age'])
Output:
Example 2:
Python3
# import module
import seaborn
seaborn.set(style = 'whitegrid')
# read csv and plot
data = pandas.read_csv("nba.csv")
seaborn.violinplot(x ="Age", y
="Weight",data = data)
Output: