Data Visualisation and Exploaretion using Python
By the end of this course, you will be able to:
visualise data using the appropriate plotting techniques based
on the type of data
plot different kinds of graphs such as box plot, scatter plot, line
chart, pie chart, bar graph or histogram for a given data
create graphs applying proper colour schemes, titles, labels
and, other graphical elements using various Python packages
Data visualisation is a concept of graphical representation of data or
information using visual elements like graphs, charts and maps.
This representation helps us in understanding patterns, trends, and
outliers in the data.
With the increase in volume of the data, discovering patterns in the
data becomes challenging. Through data visualisation, a huge
chunk of complex data can be displayed to be
easily comprehensible as well as pleasing to the eyes.
Data visualisation:
helps in finding patterns and connections between variables
requires less effort from the reader to understand the visuals
condenses a large amount of information into a small space
for quick analysis
provides relevant answers and clarity on certain questions
swiftly
Thus, data visualisation finds applications across various domains.
One of the common graphical techniques to represent data is a
plot.
Plots provide a pictorial representation of the relationship between
two or more variables in a dataset. They are important in statistics
and data analysis for deriving insights from large datasets. Some of
the examples of plots include box plot, scatter plot, line chart, bar
graph, histogram, etc.
Key elements of a plot are as shown below:
Scenario - Why Visualisation?
Let us understand the importance of data visualisation using a
sample dataset which consists of total number of passengers
traveling each month on an international airline between 1949 and
1960.
As an analyst, you would be interested in finding patterns in the
given data such as:
number of passengers travelling on an yearly basis
repeatedly observable pattern in the number of passengers
traveling every year
If the data consisted of millions of rows and hundreds of columns,
then finding such patterns in it might be time-consuming, which is
not desirable.
An Alternative Approach
Applying data visualisation techniques on the sample dataset the
following plot is generated:
You can now observe with ease that:
number of passengers has increased over the years (refer the
first graph above)
there is a peak in the middle of each year during the months of
July and August (refer the second graph above)
Thus, visualisation helped in finding the patterns quickly. This is an
effective technique for finding patterns in large datasets as well.
Data Visualisation Stakeholders
There could potentially be two types of visualisations based on the
types of stakeholders involved.
1. For self-consumption during data exploration, feature
engineering, etc.
2. For presenting or communicating the insights (from the data)
with a target audience, typically decision makers. This sort of
visualisation is usually performed to prepare the final
results/reports that may enable the target audience in decision
making.
Variety in Data
In the digital world, there has been exponential growth in data
collection. The visualisation and the analysis of this data can
provide insights that can be used for business benefits.
The different types of data collected from various sources are as
follows:
Temporal Data: Data with a time component attached to
it. For example, opening and closing values of stocks in a
year. A plot that can represent the sequence in this data and
the pattern changes over time is required.
Geospatial Data: Data with a physical location as an attribute.
For example, location of volcanoes around the world. A plot
that can represent this data on a geographical map is
required.
Topical Data: Data concerned with topics. For example,
feedback from customers. A plot that can represent the
relationships in this data is required.
Network Data: Data in the form of nodes and links between
nodes. For example, social networking data. A plot that can
represent the relationship between nodes is required.
Tree Data: Data which is basically network data but with some
hierarchy in it. For example, organisational structure. A plot
that can represent the tree structure is required.
Generally, data can be of two types:
1. Qualitative/Categorical Data: Data that deals with
characteristics and descriptions. It is further categorised as:
Binary: Data that is dichotomous. For example, True/False,
Yes/No, 1/0 etc.
Nominal: Data with no ordering or ranking. For example,
different colors, blood groups, nationality etc.
Ordinal: Data with specific order or ranking. For
example, height (short, medium, tall), income (low, medium,
high), etc.
2. Quantitative/Numerical Data: Data that is numerical in
nature and can be measured. It is further categorised as:
Discrete: Data that can be counted (whole numbers). For
example, number of floors in a building, number of students in
a classroom, etc.
Continuous: Data that can take any value within a range. For
example, weight, mileage of a car, etc.
Thus, in data visualisation, different types of plots are required to
represent the different types of available data and to fit the needs of
various stakeholders.
Visualisation Constructs
The different types of plots that can be used for data visualisation
are listed as follows:
Box plot
Scatter plot
Line chart
Bar graph
Histogram
Distplot
Pie chart
Joint plot
Pair plot
Heat map
Statistical Concepts Refresher
Data analysts perform exploratory data analysis to handle missing
values, outliers, etc. and analyse the relationship between the
variables. Data analysts require the knowledge of statistical
concepts used in data analysis to:
select the right type of graph
infer information like outliers, correlation of variables,
redundant features etc.
In this section, few statistical concepts will be explained to help you
understand different graphs.
Outliers
Outliers are the extreme values present in the dataset. They affect
the properties of data like mean and variance which are used in
model building. Hence, they may impact the accuracy of the model.
So, the question that arises is, how to know if a value is an outlier?
And how to deal with such values? Let us find out.
Quartiles
Quartiles divide the number of data points into four equal-sized
groups, or quarters.
Following are the steps to find quartiles:
1. sort the dataset in ascending order
2. find median of the sorted dataset (median divides the dataset
into two halves - Quartile 2 or Q2)
3. repeat step 2 with the first and second half of the data (this
gives Q1 and Q3, dividing the dataset into four equal parts)
With the help of quartiles, a value called Inter-Quartile Range (IQR)
can be calculated using the formula:
IQR = Q3 - Q1
Inter-Quartile Range
Inter-Quartile Range also called mid-spread, H-spread, or IQR,
indicates where most of the data is lying.
As IQR is calculated using the median, the outlying values don not
affect it. A formula is used to calculate the upper limit and lower
limit of this range. Any data point lying outside these limits is an
outlier.
Upper Limit: Q3 + (1.5 * IQR)
Lower Limit: Q1 – (1.5 * IQR)
Box Plot
A box plot gives good indication of the distribution of data about the
median. Boxplots are a standardised way of displaying the
distribution of data based on a five-number summary (minimum,
first quartile (Q1), median, third quartile (Q3), and maximum).
Scatter Plot
A scatter plot uses dots or markers to represent a value in the
hyperplane. The position of each point corresponds to the value or
properties of a tuple. The scatter plot is one of the simplest plots
which can accept both quantitative and qualitative values, with a
wide variety of applications in primitive data analysis.
Several meaningful insights can be drawn from a scatter plot, like
the ones listed below:
Finding Correlation Between Variables
Scatter plots are often used to identify the type of correlation
between variables before diving deeper into predictions. The figure
below depicts the typical scatter plots indicating the type of
correlations.
Identifying Patterns in Data
Visualising the tuples as scatter plots can be useful to spot gaps in
the values and hence identify the data points crucial to the dataset.
It can help draw decisive inferences about the type of predictor or
classifier to be used.
The figure below depicts the typical scatter plots to help identify
patterns.
Line Chart
A line chart is drawn by interconnecting all data points using straight
line segments. It is used to analyse historic variations and trends in
data. The individual data points are chronologically connected to
obtain the patterns and draw meaningful inferences. For example,
times series data.
As shown below, the first figure depicts the line chart of an
organized collection, while the second figure depicts the line chart
of an unorganized collection. Thus, when then data is sorted the
line chart is easy to infer. Whereas, when the data is not sorted a
messy line chart is generated.
Bar Chart
A bar chart is a graph with rectangular bars that compares different
categories. Each bar represents a particular category and the
length of a bar indicates the total number of values or items in that
category.
Bar charts can be plotted vertically or horizontally, but vertical bar
chart is the most common type. There are multiple variations of bar
charts including multiple, stacked, error bars, etc. to cater to various
visualisations and presentation needs.
The figure below shows a bar chart depicting the number of
cars manufactured by different companies.
Histogram
A histogram represents data as rectangular bars. Unlike the bar
chart, it is used for continuous data. Each bar groups the numbers
into intervals (bins) and the height of the bar is based on the
number of values that fall into the corresponding intervals.
A histogram is ideally suited to obtain the frequency distribution of a
given data, as depicted in the figure below.
Pie Chart
A pie chart divides the entire dataset into distinct groups. The chart
consists of a circle split into slices and each slice represents a
group. The size of the slice is proportional to the number of items in
each group compared to the others.
The sum of the slices in a pie chart is always 100%, as depicted in
the figure below.
Dist Plot
A dist plot or distribution plot, depicts the variation in a data
distribution. It represents the overall distribution of continuous data
variables.
The dist plot depicts the data by a histogram and a line in
combination with it, as shown in the figure below.
Joint Plot
A joint plot is a combination of two univariate and one bivariate
plots. The bivariate plot (in the center) helps in analysing the
relationship between two variables. The univariate plot describes
the distribution of data in each variable as a marginal plot.
A joint plot is used to quickly visualise and analyse the relationship
between two variables and examine their distributions on the same
plot, as shown in the figure below.
Pair Plot
A pair plot depicts pairwise relationships between all the
variables in a dataset in a matrix format. Each row and column in
the matrix represents a variable in the dataset.
The plots present in the diagonal are univariate plots as the
variables are compared with themselves and the others are
bivariate scatter plots, as shown in the figure below.
Heat Map
A heat map is a graphical representation of data where
similar values are depicted by the same colours. The colours vary
based on the intensity of the results.
One example for heat map is to find the correlation between the
variables in a dataset, as depicted in the figure below.
Network Graph
A network is a set of objects (called nodes or vertices) that are
connected to each other. The connections between the nodes are
called edges or links.
If the edges in a network are directed, i.e., pointing in only one
direction, the network is called a directed network. When drawing a
directed network, the edges are typically drawn as arrows indicating
the direction.
If all edges are bidirectional, or undirectional, the network is an
undirected network.
The figure below depicts the concept of a network graph.
Word Cloud
A word cloud is a visual representation of free form text, which is
like a collage. It is typically used to depict keyword metadata of
websites, articles, reviews, feedbacks etc. The frequency and
significance of the words are depicted by the font, font size and
colour of the text in the cluster.
Words with greater significance and occurrence are depicted in a
bigger and bolder font towards the central location of the cluster
and other latent words occupy peripheral places with smaller fonts
and faded colors. Most insignificant words, stop words, irrelevant
information is eliminated from the cluster while plotting it.
A word cloud finds its usage more in Natural Language Processing.
The picture below depicts the concept of a word cloud.
Choropleth Maps
A choropleth map is a pictorial representation of data on a
geographical map. The intensity of color in a region on the map
corresponds to the respective values.
The figure below depicts the choropleth map of Covid-19
distribution in India as of 14th October, 2020. It represents the count
of the spread on the given date. A deeper shade corresponds to a
higher value while a lighter shade marks the safe regions.
Data Visualisation Libraries in Python
Few of the popular Python libraries used for data visualisation are
listed as follows:
Matplotlib
Seaborn
Plotly
Let us briefly discuss each of them.
Matplotlib
Matplotlib is one of the most basic and popular Python libraries
used for data visualisation. It is developed for imitating the plotting
capabilities of MATLAB, another programming environment.
'[Link]' is used for two dimensional graphics in Python
programming. It can be used in Python shell, scripts, web
application servers, and other graphical user interface toolkits. It is
heavily dependent on other Python libraries such as numpy, which
is considered as a major drawback.
Installing Matplotlib
!pip install matplotlib
Seaborn is a statistical data visualisation library in Python. It is
integrated to work with Pandas dataframes with a more straight
forward approach.
Seaborn extends the plotting capabilities of matplotlib and provides
a high-level interface to generate attractive plots that are visually
appealing.
Installing Seaborn
!pip install seaborn
Plotly is another data visualisation library that is used to generate
highly interactive plots.
Installing Plotly
!pip install plotly
Quiz
Transactional data of an e-commerce site can be classified as which of the following?
Temporal data
Geospatial data
Topical data
Network data
Tree data
Q2 of 5
Which of the following is a type of qualitative data?
Ordinal
Nominal
Binary
All of the above
Q3 of 5
State True/False: Quartiles are calculated using mean.
True
False
Q4 of 5
In a class of 1000 students, it is required to plot the distribution of marks scored by students
in an exam. Which of the following graphs can be used?
Histogram
Stacked Bar Plot
Error Bar Plot
Pie Chart
Q5 of 5
Which graph helps us understand the pairwise relationship between the parameters of a
dataset?
Pair Plot
Dist Plot
Heat Map
Joint Plot
Use Case
Let us consider a use case, where a cutomer wishes to buy a car.
Following are some of the questions that the customer might have
before the purchase.
What is the price range of different cars available in the
market?
What is the range of horsepower and mileage of various cars?
Does a car with higher horsepower give lower mileage?
How much leg space does the car have?
How many passengers can the car carry based on its type?
Let us use 'Cars93' dataset to answer the above
questions. Click here to downloaded the dataset.
The information that the columns of this dataset contain is given
below:
Now, let us import the dataset using the code given below:
#Importing the necessary Libraries
import numpy as np
import pandas as pd
import [Link] as plt
import [Link] as cm
#Importing the required dataset
cars_df = pd.read_csv("Data/[Link]")
columns = ["Manufacturer","Model","Type","Price",
"[Link]","[Link]","Horsepower","[Link]","Pass
engers"]
cars_df[columns].head()
A sample of the dataset for the columns selected in the code above
is shown below:
Let us first identify the price range of the cars in the dataset.
Box Plot
The price range of the cars can be represented using a box plot. It
is a graphical way of depicting the five-number summary as
discussed in the Introduction to Probability and Statistics course.
Matplotlib works efficiently with dataframes and arrays. So, Pandas
DataFrame can be used as they have some functionality of
matplotlib built-in to create visualisations. You will notice that the
same method is followed thoughtout this module.
The Python code to create a box plot for the price range of cars
using cars_df["Price"] column, is given below:
#creating a box plot for the variable 'Price'
cars_df["Price"].plot(kind="box",figsize = (10,7))
plot( ) is a method of the DataFrame that takes a parameter 'kind'
for displaying the appropriate visualisation. For example, the word
'box' is used to generate a box plot. Similarly, other visualisations
are generated if values like bar, line, scatter, etc. are used as the
'kind' parameter.
For more details on plot features, refer to '[Link]'
section of the Pandas documentation.
The box plot is also called a whiskers plot. In case the data contains
outliers, then the extreme lines (called whiskers) represent 1.5
times the IQR value from Q1 and Q3 respectively. Outliers here are
the values that are outside the range described by 1.5 times IQR
value from Q1 and Q3.
The skewness of data can also be identified from the visualisation
of a box plot. Since the box in the above plot is towards the
minimum, this data is right-skewed. Similarly, if the data is left-
skewed, then the box would be towards the maximum.
Mathematically:
Outliers < Q1 - 1.5 (IQR)
Outliers > Q3 + 1.5 (IQR)
It can be observed that, if the outliers are excluded, then:
minimum price of a car comes close to 10 thousand dollars
and maximum price comes close to 40 thousand dollars
most cars are priced approximately between 11 thousand
dollars to 22 thousand dollars
But is car price the only parameter that needs to be considered
while purchasing a car? The answer is NO.
Let us tap into the other features of the cars to find the best-suited
car for the customer.
Box Plot Using Sub Plots
Often, there is a need to display the distribution of multiple features
together for better understanding.
Let us learn how to plot the graphs alongside each other.
Let us use the subplots functionality of '[Link]' to create a
grid-like system based on the number of rows and columns
provided, as shown in the code below:
#The following lines enable us to use subplot functionality
fig, (ax1, ax2) = [Link](2, 1)
fig.set_figwidth(10) #setting the width for the plot
fig.set_figheight(7) #setting the height for the plot
The subplots method returns a figure object and axes objects and
their functionality is as follows:
Figure object: It controls the structure of the plot as shown above,
where the height and width of the plot needs to be set.
Axes object: It controls what exists in the plot like labels, data, text
etc.
The number of axes objects depend on the number of elements in
that grid. For example, if there are two elements, there will be two
axes objects.
Let us use the axes objects to create boxplots alongside each other
for the range of horsepower and mileage of cars, as shown in the
code below:
#The following lines enable us to use subplot functionality
fig, (ax1, ax2) = [Link](2, 1)
fig.set_figwidth(10)
fig.set_figheight(7)
#The following lines of code change the alignment from vertical to
horizontal
[Link](cars_df["Horsepower"],vert=False)
[Link](cars_df["[Link]"],vert=False)
The output of the above code is given below:
Both horsepower and mileage are plotted together. However, it is
difficult to recognise the plots that represent the
respective variables.
How can the plot be improved?
Will the use of labels and titles enhance the readability of this plot?
Let us add labels to the plots to make it more concise. To do so, the
axes objects can be used to set the title for each plot, as follows:
set_title method sets the title for each plot with default position
as top of the plot
set_xlabel sets the text for x-axis which usually describes the
nature of the axis
Similarly, there is y_label for y-axis which will be discussed later in
this course.
The code to enhance the plot is given below:
#The following lines enable us to use subplot funtionality
fig, (ax1, ax2) = [Link](2, 1)
fig.set_figwidth(10)
fig.set_figheight(7)
#The following lines of code change the alignment from vertical to
horizontal
[Link](cars_df["Horsepower"],vert=False)
[Link](cars_df["[Link]"],vert=False)
#The following lines of code are used to add labels to axes and title
to the graph
ax1.set_title('Horsepower')
ax1.set_xlabel('Horsepower')
ax2.set_title('City Mileage')
ax2.set_xlabel("City Mileage (in miles per US gallon)")
The output of the above code is given below:
It can be seen from the above graph that adding labels to the plots
made them more readable and intelligible. But there is an issue with
the 'City Mileage' title as it is overlapping with the x-axis label of the
first plot.
To avoid such issues, the tight_layout method of pyplot in matplotlib
is used, as shown below:
#The following lines enable us to use subplot functionality
fig, (ax1, ax2) = [Link](2, 1)
fig.set_figwidth(10)
fig.set_figheight(7)
#The following lines of code change the alignment from vertical to
horizontal
[Link](cars_df["Horsepower"],vert=False)
[Link](cars_df["[Link]"],vert=False)
#The following lines of code are used to add axis labels and titles to
the graph
ax1.set_title('Horsepower')
ax1.set_xlabel('Horsepower')
ax2.set_title('City Mileage')
ax2.set_xlabel("City Mileage (in miles per US gallon)")
#In case of any superimposition of the subplots, the following
functions caters the aesthetics
fig.tight_layout()
This will arrange all the elements of the plot without any
overlapping. The output after applying the tight layout is shown
below:
From the above graph, it can be understood that the plot on the top
is for 'Horsepower' and in the bottom is for 'City Mileage'.
It can also be observed that the range of horsepower without
outliers is in order of 60 – 260 while that of mileage is 15 – 34 MPG.
Multiple Box Plots
Let us find the price range of cars for each car type by plotting
different box plots, as shown below:
# Setting up the partitions, length and width of the figure
fig, ax = [Link](2, 3)
fig.set_figwidth(10)
fig.set_figheight(7)
#title
[Link]("Multiple Box Plots", fontsize=16)
#Accessing each partition[m][n] and providing the plot and its title
ax[0][0].boxplot(cars_df["Price"][cars_df["Type"]=="Compact"])
ax[0][0].set_title('Compact')
ax[0][1].boxplot(cars_df["Price"][cars_df["Type"]=="Large"])
ax[0][1].set_title('Large')
ax[0][2].boxplot(cars_df["Price"][cars_df["Type"]=="Midsize"])
ax[0][2].set_title('Midsize')
ax[1][0].boxplot(cars_df["Price"][cars_df["Type"]=="Small"])
ax[1][0].set_title('Small')
ax[1][1].boxplot(cars_df["Price"][cars_df["Type"]=="Sporty"])
ax[1][1].set_title('Sporty')
ax[1][2].boxplot(cars_df["Price"][cars_df["Type"]=="Van"])
ax[1][2].set_title('Van')
The output of the above code is given below:
'[Link]' method creates a grid-like system of dimensions 2x3
and returns the figure and axis objects using which, individual
subplots can be plotted. As it follows the zero-index system, the
two-dimensional matrix style can be used for accessing each
subplot. Here, 'set_figwidth' and 'set_figheight' methods of the
figure object achieve the desired size of the figure and
improve readability.
Multiple Box Plots in Same Canvas
Until now all plots in the subplot were plotted individually, due to
which they could not be compared. Therefore, let us try to plot box
plots of different types of cars in one plot so that all these plots are
plotted in the same canvas and are comparable.
#Finding the list of unique values of 'car type'
car_type_list = cars_df["Type"].unique()
#setting the width and height of the plot
fig, ax = [Link]()
fig.set_figwidth(10)
fig.set_figheight(7)
#creating a box plot for every unique car type
[Link]([cars_df["Price"][cars_df["Type"]==k] for k in
car_type_list])
#To set the position for each plots in the iteration
[Link]([i for i in range(1,len(car_type_list)+1)],[k for k in
car_type_list])
#super-title
[Link]("Prices of car according to car type", fontsize=16, y = 1)
The output of the above code is shown below:
Now that all the boxplots are plotted successfully under the same
axes, let us break down the code to see how each line helped in
achieving this.
Code Breakup
1. First, the unique values of the Type feature need to be identified.
car_type_list = cars_df["Type"].unique()
car_type_list
Output: array(['Small', 'Midsize', 'Compact', 'Large', 'Sporty',
'Van'], dtype=object)
2. Next, the list comprehension can be used to create a list of
values which contain the data required for plotting each box plot.
Each item in the list is the data associated with each type of car in
the car_type_list.
car_type_list = cars_df["Type"].unique()
fig, ax = [Link]()
fig.set_figwidth(10)
fig.set_figheight(7)
[Link]([cars_df["Price"][cars_df["Type"]==k] for k in
car_type_list])
The output of the code above is shown below:
You can notice that the dimensions in the subplots method are not
mentioned. In such cases, the axis object takes the default value (1,
1)
Multiple Box Plots with Same Axes
Another way to create a box plot is by using the 'grid' method. Let
us modify the code in the previous page by using the 'sharey' and
'sharex' properties of the subplots, as shown below:
#setting the plot, width and height
fig, ax = [Link](2, 3, sharey=True, sharex=True)
fig.set_figwidth(10)
fig.set_figheight(7)
#super-title
[Link]("Multiple Box Plots", fontsize=16)
#accessing and creating the respective sub-plots
ax[0][0].boxplot(cars_df["Price"][cars_df["Type"]=="Compact"])
ax[0][0].set_title('Compact')
ax[0][1].boxplot(cars_df["Price"][cars_df["Type"]=="Large"])
ax[0][1].set_title('Large')
ax[0][2].boxplot(cars_df["Price"][cars_df["Type"]=="Midsize"])
ax[0][2].set_title('Midsize')
ax[1][0].boxplot(cars_df["Price"][cars_df["Type"]=="Small"])
ax[1][0].set_title('Small')
ax[1][1].boxplot(cars_df["Price"][cars_df["Type"]=="Sporty"])
ax[1][1].set_title('Sporty')
ax[1][2].boxplot(cars_df["Price"][cars_df["Type"]=="Van"])
ax[1][2].set_title('Van')
The output given below has been generated by using 'sharey =
True' and 'sharex = True'.
The different types of cars along with their prices can now be easily
compared. Many other things can also be infered from the above
visualisation. For example,
vans have the smallest price range, whereas midsize cars
have the largest price range
small cars have the lowest price, whereas large cars have the
highest price
Scatter Plot
Now that you know the individual ranges of both horsepower and
mileage, let us find if there is any relationship between them.
Plotting these values against each other might reveal the presence
of a relationship among them.
#To Plot the data as a scatter plot
ax = cars_df.plot(["Horsepower"],["[Link]"],kind="scatter", color =
"black",marker = "*",figsize=(10,7))
#To add labels and title to the output
ax.set_xlabel("Horsepower") #sets label for x-axis
ax.set_ylabel("[Link]") #sets label for y-axis
ax.set_title("Horsepower vs [Link]",fontsize=16) #sets title for the
graph
The output of the above code is given below:
Since the scatter plot is a 2D plot, the x and y are passed in the
same order as shown in the above code. The parameters 'color'
and 'marker' can be used to adjust the colour and shape of the
points shown in the plot. For example, black asterisks are used for
displaying each data point.
Here, it can be observed that as horsepower increases the mileage
is likely to decrease.
Now let us understand the relationship between horsepower and
mileage based on car type.
By now you know the unique values of the car type in the previous
plots. The same list is used to create a scatter plot between
horsepower and mileage.
fig = [Link]()
fig.set_figwidth(10)
fig.set_figheight(7)
colors = cm.seismic_r([Link](0, 1, len(car_type_list)))
# We extract the colours using the 'seismic_r' method. Here,
'r' indicates the reverse.
for car_type,c in zip(car_type_list,colors): # for every
car type in the car_type_list we plot all the points in the
scatter plot
x = cars_df[cars_df["Type"] == car_type]["Horsepower"]
y = cars_df[cars_df["Type"] == car_type]["[Link]"]
[Link](x,y,color = c,label=car_type)
[Link]("Scatter plot of horsepower and
mileage",fontsize=16)
[Link]("Horsepower")
[Link]("Mileage City")
[Link]()
The output of the above code is given below:
From the scatter plot it can be understood that higher the
horsepower, lower the milage of a car in a city. It can also be
deduced that vans give the least mileage in a city whereas
small cars are the best fit though they have the least horsepower.
Line Chart
A line chart is a type of chart that displays information as a series of
data points connected by straight line segments.
Sometimes multiple graphs can depict the same information. Here,
a connected scatter plot is created where the data is sorted based
on the horsepower, to get meaningful insights from the line chart.
#First sort the data to get a proper line chart
cars_df=cars_df.sort_values(by="Horsepower")
#The following lines of code create a blank canvas to plot
on
fig, ax = [Link]()
fig.set_figwidth(10)
fig.set_figheight(7)
#Data is fed and plotted using the following lines
cars_df.plot(ax = ax, x = "Horsepower", y = "[Link]",
kind = "line", )
cars_df.plot(ax = ax, x = "Horsepower",y= "[Link]", kind =
"line", linestyle='--')
The output of the above code is a line chart or a line graph and is
shown below:
You can notice that two line charts with the same axes are plotted,
unlike the box plot where subplots created multiple boxes. To do
this, the axis object, returned from the subplots( ) method is passed
to both the line charts using the 'ax' parameter. Note that the
number of rows and columns have not been passed to the subplots
method.
The plot method takes care of the colours to make each line look
distinct. Also, 'linestyle' parameter can be passed to display the
lines in different styles.
It can be observed that as horsepower increases the mileage is
likely to decrease. It can also be deduced that there is a peak in
mileage at around 100 horsepower, which was not so clear in the
scatter plot created previously.
Let us enhance the readability of this chart further by replacing the
labels, as shown in the code below:
#The following lines of code create a blank canvas to plot on
fig, ax = [Link]()
fig.set_figwidth(10)
fig.set_figheight(7)
#Data is fed and plotted using the following lines
cars_df.plot(ax = ax, x = "Horsepower", y = "[Link]", kind =
"line", )
cars_df.plot(ax = ax, x = "Horsepower",y= "[Link]", kind = "line",
linestyle='--')
#The following part of code adds labels and titles to make the graph
readable
ax.set_ylabel("Mileage in (mile per US gallon)")
ax.set_title("Mileage vs Horsepower",fontsize=16)
It can be observed that the graph is not ambiguous anymore and
depicts all information as intended.\
So far, you have become familiar with plotting two features for
different types of cars. Now, let us consider a different scenario,
where the requirement is to compare various features. For example,
in the 'Cars93' dataset, it is required to observe the variations in
'[Link]', 'Engine Size', '[Link]' and 'RPM' against
'Horsepower'. The line chart can be used for this purpose to aptly
show the fluctuations.
The 'plot' method in '[Link]' creates a line chart. It takes
two parameters x values and y values, both numerical in nature.
Notice that RPM has been divided by 100 to maintain the scale of
the graph because of its high values.
The code for the above requirement is given below:
#First sort the data to get a proper line chart
cars_df=cars_df.sort_values(by="Horsepower")
#Plotting
fig = [Link]()
fig.set_figwidth(10)
fig.set_figheight(7)
[Link](cars_df["Horsepower"], cars_df["[Link]"],label="[Link]")
[Link](cars_df["Horsepower"], cars_df["EngineSize"], label="Engine
Size")
[Link](cars_df["Horsepower"], cars_df["[Link]"],
label="[Link]")
[Link](cars_df["Horsepower"], [i/100 for i in
cars_df["RPM"]],label="RPM")
[Link]("Horsepower vs Mileage in city, Engine size, Mileage on
highway, RPM",fontsize=16)
[Link]("Horsepower")
[Link]("Mileage in city, Engine size, Mileage on highway, RPM")
[Link]()
The output of the above code is given below:
It can be observed that horsepower does not have a major impact
on engine size. On the other hand, it unpredictably affects
RPM. The effects of high horsepower remain the same on
mileage. Although mileage of a car in a city is affected a little more
than its mileage on a highway.
A line chart can also be created vertically, by inverting the previous
line chart 90 degrees to the right. To do so 'x' and 'y' in the 'plot'
method can just be interchanged as shown below:
fig = [Link]()
fig.set_figwidth(10)
fig.set_figheight(9)
[Link](cars_df["[Link]"],cars_df["Horsepower"],label="[Link]")
[Link](cars_df["EngineSize"],cars_df["Horsepower"],label="Engine
Size")
[Link](cars_df["[Link]"],cars_df["Horsepower"],label="[Link]
y")
[Link]([i/100 for i in
cars_df["RPM"]],cars_df["Horsepower"],label="RPM") #interchanging x and
y
[Link]("Mileage in city, Engine size, Mileage on highway, RPM vs
Horsepower",fontsize=15)
[Link]("Horsepower")
[Link]("Mileage in city, Engine size, Mileage on highway, RPM")
[Link]()
The output of the above code is given below:
Bar Chart
Box plot, scatter plot, or line chart fail when there is a need to plot
both categorical and numerical data, as they can only take
numerical data. Then, how to find relationships between such types
of data? Which graph can be used?
The answer to the questions above is a bar chart or a bar graph. A
bar chart takes in two features, 'x' and 'y' as inputs. 'x' is the
categorical data plotted against 'y' which is the numerical data. The
following code shows a simple bar chart between 'DriveTrain' and
'[Link]' along with the plot aesthetics.
#width,height
fig = [Link]()
fig.set_figwidth(10)
fig.set_figheight(7)
#code to create bar chart
[Link](cars_df["DriveTrain"],
cars_df["[Link]"],width=0.2,label="Mileage in city")
#title and label
[Link]("DriveTrain vs [Link]",fontsize=16)
[Link]("DriveTrain")
[Link]("[Link]")
#legend
[Link]()
The output of the above code is shown below:
A bar chart can also be plotted horizontally using the barh() method
from 'matplotlib'.
Notice that the first argument is still categorical data. Also, observe
that the axes labels have been changed accordingly.
#horizontal bar graph
[Link](cars_df["DriveTrain"],
cars_df["[Link]"],height=0.2,label="Mileage in city")
[Link]("[Link]")
[Link]("DriveTrain")
The output of the above code is shown below:
Consider the type of data with multiple categories. Assue, there is a
need to plot a graph using different colours representing each
category.
Let us consider 'Passengers' and 'Type' from the 'Cars93' dataset.
#Use the following code snippet to filter the unique values
of no. of passengers a car can carry
cars_df["Passengers"].unique()
Output: array([4, 5, 6, 7, 8, 2], dtype=int64
#Use the following code snippet to filter the unique values
of Types of car.
cars_df["Type"].unique()
Output: array(['Small', 'Sporty', 'Compact', 'Midsize', 'Van', 'Large'],
dtype=object)
Let us find the number of each type of car for each passenger
capacity. The data can be prepared for plotting by using the code
below:
#Use the following code snippet to filter the data and
obtain the target columns into a separate dataframe.
grouped_data = cars_df[["Passengers","Type"]].groupby(by =
["Passengers","Type"]).size().unstack().reset_index()
Let us analyse the above code to understand how each of the three
methods modifies the data.
1. size() after groupby() returns the frequency for each 'Type'.
grouped_data = cars_df[["Passengers","Type"]].groupby(by=
["Passengers","Type"]).size()
Output:
2. unstack() uses 'Passengers' as pivot and converts the above
data to a dataframe as shown below:
grouped_data = cars_df[["Passengers","Type"]].groupby(by=
["Passengers","Type"]).size().unstack()
Output:
3. reset_index() as the name suggests, resets the index of the
above dataframe as shown below:
grouped_data = cars_df[["Passengers","Type"]].groupby(by=
["Passengers","Type"]).size().unstack().reset_index()
Output:
The NaN values seen in the output above will be ignored.
Let us proceed further and plot the data for each type of car using
bar() as shown in the code below:
#Stacked Bar Graph can be plotted using the grouped data, as
follows:
grouped_data.plot(x="Passengers",kind="bar",stacked=True,col
ormap=[Link],figsize=(10,7))
The output of the above code is shown below:
Matplotlib has built-in colormaps. Here, 'Paired' is used. Refer to
'[Link]' documentation for more colormap options.
Note: The three methods in the above code, size(), unstack() and
reset_index() have been utilized for demonstration purposes
and are required only on a case to case basis.
Error bars on a cartesian graph are a graphical enhancement to
visualise the variability of plotted data. They are used on graphs to
indicate the uncertainty in a reported measurement. A general idea
of how precise a measurement is, can be obtained by using error
bar charts.
Let us use the same features and data from the previous page.
Error bars can be added to the plot using 'yerr' or 'xerr' feature of
bar() and barh() methods. They are used to plot the standard
deviation, maximum-minimum or confidence intervals in a dataset.
In the code given below, the standard deviation is plotted. Observe
that a different colormap called 'seismic' has been used.
#Error bars can be added to the stacked bar graph with the
'yerr' argument as follows
grouped_data.plot(x="Passengers",kind="bar",stacked=True,col
ormap=[Link],figsize=(10,7),yerr=[Link](cars_df["Passeng
ers"]))
The output of the above code is the graph shown below. The black
lines parallel to one of the axes are the error bars. This graph is
interpreted by the length of the error bar. Longer the bar, more the
deviation and shorter line indicates less deviation from the data.
Note: Error bars are not unique to the bar plot. They can also be
used with other plots like scatter plot or line chart. You are
encouraged to explore more about error bars for other plots.
Let us discuss the grouped bar chart where the bars are stacked
beside each other to show the difference between multiple features
used on 'x' to the values of 'y'.
Assume, there is a need to see how each type of 'DriveTrain'
performs based on '[Link]', '[Link]' and 'RPM'.
First, let us see the unique values in 'DriveTrain'.
cars_df["DriveTrain"].unique()
Output: array(['Front', '4WD', 'Rear'], dtype=object)
Let us group the features based on 'DriveTrain' and get their sum.
grouped_cars =
cars_df[["[Link]","[Link]","RPM","DriveTrain"]].group
by(by="DriveTrain").mean().T
grouped_cars
Output:
Before plotting the above features, to have an even chart, RPM
needs to be scaled as it has high values. For this purpose, RPM is
divided by 100.
Now, let us plot the bar chart using the code given below:
fig = [Link]()
fig.set_figwidth(10)
fig.set_figheight(7)
grouped_cars.loc['RPM'] /= 100
width=0.2 # We assign the value of the width of the bar and
on the number of groups.
ind=list(range(len(cars_df['DriveTrain'].unique())))
[Link]([i for i in ind], height=grouped_cars["4WD"],
label="4WD", width=width)
[Link]([i+width for i in ind],
height=grouped_cars["Front"], width=width, bottom=0,
label="Front")
[Link]([i+width*2 for i in ind],
height=grouped_cars["Rear"], label="Rear", width=width,
bottom=0)
[Link]("Mileage in city, Mileage on highway,RPM vs
DriveTrain", fontsize=16)
[Link]("Mileage in city, Mileage in highway, RPM")
[Link]("Average per DriveTrain type")
[Link]([i+width for i in ind],["Mileage in
City","Mileage in Highway","RPM"])
[Link]()
The output of the above code is shown below:
Let us analyse the code to understand the bar chart shown above,
as follows:
1. The bar chart is plotted with the first argument 'x' which can be
manipulated to set the position of the bar on the x-axis. Height or 'y'
of the bar is the value from the 'grouped_cars' dataframe.
[Link]([i for i in ind], height=grouped_cars["4WD"],
label="4WD", width=width)
[Link]([i+width for i in ind],
height=grouped_cars["Front"], width=width, bottom=0,
label="Front")
[Link]([i+width*2 for i in ind],
height=grouped_cars["Rear"], label="Rear", width=width,
bottom=0)
2. In bar plots, the 'xticks' of the bar must be assigned. If not
specified, their values would be equal to the values assigned to 'ind'
variable, shown in the code above. To position the 'xticks' at the
center for each of the three grouped bars, 'i+width' is used.
[Link]([i+width for i in ind],["Mileage in
City","Mileage in Highway","RPM"])
Pie Chart
Assume, there is a need to find the number of cars based on the
number of cylinders they contain.
First, let us see the unique number of cylinders a car contains.
cars_df["Cylinders"].unique()
Output: array(['4', '6', '8', '3', 'rotary', '5'], dtype=object)
For graphical representation, let us create a pie chart using the
code given below:
grouped_data = cars_df[["Cylinders", "Type"]].groupby(by =
["Cylinders", "Type"]).size().unstack()
fig, ax = [Link](2,3, figsize = (15,10))
grouped_data.[Link](ax = ax, subplots = True, fontsize =
20)
[Link]("Number of cars for each type of cylinders",
fontsize=26, x = 1, y = 2.1)
fig.tight_layout(rect=[0,0,2,2])
The output of the above code is the pie chart shown below,
which clearly depicts the distribution of number of cylinders of
different types of cars.
Let us analyse the code to understand the pie chart shown above,
as follows:
1. The data is grouped on 'Cylinders' and 'Type' using the groupby()
method.
grouped_data = cars_df[["Cylinders", "Type"]].groupby(by =
["Cylinders", "Type"]).size().unstack()
2. The pie() method returns patches, texts, and autotexts. Patches
control individual slices of the pie chart. Refer to the documentation
to know more about the return values.
fig, ax = [Link](2, 3, figsize = (15,10))
grouped_data.[Link](ax = ax, subplots = True, fontsize=20)
[Link]("Number of cars for each type of cylinders ",
fontsize=26,x = 1, y = 2.1)
3. The 'tight_layout' is used to create a rectangle. The 'rect' feature
takes in a list of values that represent the sides of the rectangle in
the following order:
left
bottom
right
top
fig.tight_layout(rect=[0,0,2,2])
Parameters like explode, legend, autopct, etc. can be used to make
a pie chart more informative. The 'explode' parameter explodes or
pops out the slice that needs to be highlighted. The 'legend'
parameter gives information about what data each slice is
representing; like in this scenario, the legend is representing the
number of cylinders each type of car contains. The 'autopct'
parameter gives the format to the labels as per the user.
Histogram
A histogram is a graphical representation of the distribution of
numerical data. In a histogram, the height of the bar represents the
frequency in the class interval for that dataset.
Assume, there is a need to plot the range of mileage under which
most cars fall. For graphical representation, let us plot a histogram
using the code given below:
cars_df["[Link]"].plot(kind="hist", grid=True,
figsize=(10,7), bins=6)
[Link]("Distribution of [Link]", fontsize=16)
[Link]()
The output of the above code is a histogram, as shown below, from
which it can be inferred that most cars have a mileage between 15
and 20.
The 'grid' parameter whose default value is False, can be omitted
as shown in the graph below.
To get more specific information, the class interval of the data can
be changed using the 'bins' parameter. Let us increase the number
of bins from 6 to 20, as shown in the code below:
cars_df["[Link]"].plot(kind="hist", bins=20,
figsize=(10,7))
[Link]("Distribution of [Link]", fontsize=16)
[Link]()
The output of the above code is a histogram, as shown below, from
which it can be inferred that most cars have a mileage in the range
of 16 to 18, if we consider the range to be in intervals of two.
The above graph is difficult to read because of the values on the x-
axis. To address this issue, custom values can be set using the
xticks() method.
The colour of a histogram can be changed using the 'color'
parameter. It is a built-in feature of matplotlib and can take
values between C(0-9). The code below implements the above
requirements as shown below:
cars_df["[Link]"].plot(kind="hist", bins=20,
figsize=(10,7),color="C1")
[Link]("Distribution of [Link]", fontsize=16)
[Link](range(15,50))
[Link]()
The output of the above code is a histogram, as shown below, from
which it can be inferred that the highest interval is between 16 and
17.
A probability density plot can be created by making a histogram
smooth and continuous using an estimation function. It can be
useful in visualising 'shape' of the data as a continuous replacement
for a discrete histogram.
The 'kind = density' parameter plots the density line of the data. The
'density = True' parameter returns the probability densities of each
bar of the histogram. And, the xlim( ) method is used to set the limit
of the axis between 14 and 50, as shown in the code below:
cars_df["[Link]"].plot(kind="density")
cars_df["[Link]"].plot(kind="hist",bins=15,density=True,fi
gsize=(10,7))
[Link]("Distribution of [Link]",fontsize=16)
[Link](14,50)
The most common estimation function is the 'kernel density
estimation' technique that lets you create a smooth curve over a
given set of data, as shown in the plot below:
Note: A stacked histogram can also be created similar to a bar
chart. You can explore stacking by using the parameter 'stacked =
True'.
Word Cloud
The 'IPhoneX-Review' dataset contains the public reviews of the
product. Click here to download the resources used in this section.
Assume, there is a need to find the words which are most frequently
used in the reviews. Recall that feedback data is an example of
topical data.
The above requirement can be fulfilled with a frequency table or a
bar plot. But visually there is a better way to find the most used
word in a dataset by utilising a word cloud.
A word cloud is depicted in the image shown below:
The size of the words in a cloud depicts their frequency. It generally
aids in finding the topic of the text that has been plotted.
Let us load all the necessary libraries. Let us use the read_csv()
method from Pandas library to load the data into the 'phone_df'
dataframe, as shown in the code below:
#Wordcloud is a separate library used to handle the plotting
of text into an image
from wordcloud import WordCloud, STOPWORDS
import [Link] as plt
#Reading the data
phone_df =
pd.read_csv("Data/[Link]",encoding='latin')
phone_df
Output:
Stopwords are used in the set() method to remove redundant and
commonly used stopwords like a, an, the etc.
To display the word cloud for reviews from the users, all the words
used in the 'Review' column are added into the 'word_string'.
Now, a word cloud can be generated using the WordCloud()
function by passing values for 'backgroud_colour', 'stopwords',
'max_words' etc., as shown in the code below:
#The following part of code helps to concatenate the text of
the relevant column into a single string
word_string = ''
stopwords = set(STOPWORDS)
for comments in phone_df.[Link]:
word_string = word_string + comments
wordcloud =
WordCloud(background_color='black',stopwords=stopwords).gene
rate(word_string)
Let us now plot the word cloud, using the code given below:
#Creating the canvas
fig = [Link]()
fig.set_figwidth(14)
fig.set_figheight(18)
#Plotting the Wordcloud
[Link](wordcloud, interpolation='bilinear')
[Link]('off')
[Link]()
The output of the above code is shown below:
Observe that the word cloud has some obvious words like 'phone'
and 'iPhone'. If these words are not required to appear in the word
cloud, they can be added to the 'stopwords', as shown in the code
below:
#To add more words to the list of stopwords.
[Link]('phone')
[Link]('iPhone')
Now, let us regenerate the word cloud, using the code given below:
#Alternatively generating the wordcloud first
[Link](word_string)
#Now displaying the cloud
fig = [Link]()
fig.set_figwidth(14)
fig.set_figheight(18)
[Link](wordcloud, interpolation='bilinear')
[Link]('off')#Since we do not need labels on axes for a
Wordcloud
[Link]()
From the ouput of the above code shown below, it can be observed
that the newly generated word cloud does not contain the words
'phone' and 'iPhone'.
The shape of a word cloud can be changed.
Let us read an image which will provide the word cloud a custom
outline, using the code given below:
#importing necessary libraries
from [Link] import imread
from skimage import data_dir
#reading an image to set the custom outline of Wordcloud
cloud = imread('[Link]')
[Link](cloud)
The output of the above code is shown below:
Let us add the above 'cloud' as a 'mask' to the word cloud and
change its shape, using the code given below:
#plotting the custom Wordcloud
wc1 =
WordCloud(stopwords=stopwords,max_words=50,background_color=
'white',mask = cloud)
[Link](word_string)
fig = [Link]()
fig.set_figwidth(10)
fig.set_figheight(16)
[Link](wc1, interpolation='bilinear')
[Link]('off')
[Link]
The output of the above code is shown below:
Network Graph
To visualise the connection between a few points and see their
impact, a special type of plot called a network graph can be
created.
It mainly involves the following steps:
1. Creating and filling the graph
2. Plotting the graph
Matplotlib does not provide the necessary functionality to create a
network graph. Hence, 'networkx' and 'plotly' libraries are
used. 'networkx' is used for creating and populating the graph and
'plotly' for visualising the graph. While 'networkx' also provides a
'draw_networkx' method that can be used to visualise a graph, the
interactive nature of plots created using 'plotly' aid in better
visualisations.
For creating a network graph, the two essentials are:
1. Nodes: individual points in the plot
2. Edges: connections between the nodes
A network graph shows how things are interconnected and uses
link lines to represent their connections. Its helps in highlighting the
type of relationship between a group of entities. For example, it can
be used in social media network analysis.
Let us use the 'concept tag network' dataset. It is a collection of a
network of technology tags from Developer Stories on the Stack
Overflow online developer community website. It contains
information about how various technologies are related to each
other by using tag correlations. Tag correlations are measured by
how often technology tags appear together relative to how often
they appear separately at Stack Overflow.
Click here to download the datasets used in this section.
The data contains two comma-separated value files, as given
below:
1. 'StackNetworkLinks' file contains links of the network, the
source, and target tech tags plus the value of the link between
each pair.
2. 'StackNetworkNodes' file contains nodes of the network, the
name of each node, which group that node belongs to, and
node size based on how often that technology tag is used.
Let us read both the files, using the code given below:
#Importing necessary libraries
import networkx as nx
import plotly as py
import plotly.graph_objs as go
import pandas as pd
from [Link] import download_plotlyjs,
init_notebook_mode, plot, iplot
# Reading the required files
df_nodes = pd.read_csv('[Link]')
df_edges = pd.read_csv('[Link]')
G = [Link](day="Stackoverflow")
Output:
'[Link]' creates an empty graph 'G' which can be filled by using
'df_nodes' and 'df_edges' from the imported dataset, as shown in
the code below:
for index, row in df_nodes.iterrows():
G.add_node(row['name'])
for index, row in df_edges.iterrows():
G.add_weighted_edges_from([(row['source'],
row['target'], row['value'])])
Now, positions can be assigned to each of the nodes in space. To
do this, 'spring_layout' method can be used, as shown in the code
below:
pos=nx.spring_layout(G, k=0.25, iterations=50)
for n, p in [Link]():
[Link][n]['pos'] = p
'G' is the graph created above, 'k' is the optimal distance between
the nodes (if not specified, the default k value is 1/sqrt(number of
nodes)), and 'iterations' is the maximum number of iterations for the
Fruchterman-Reingold force-directed algorithm.
Note: You can explore the Fruchterman-Reingold force-directed
algorithm. However, the algorithm is out of scope for this course
keeping in mind the complexity of this course.
Now, let us create scatter plots using 'go' objects of 'plotly'. Both
edges and nodes are added to the plots. These are dictionary-like
structures and are named as 'edge_trace' and 'node_trace'
respectively, as shown in the code below:
# Adding edges to the plot
edge_trace =
[Link](x=[],y=[],line=dict(width=0.5,color='#888'),hover
info='none', mode='lines')
for edge in [Link]():
x0, y0 = [Link][edge[0]]['pos']
x1, y1 = [Link][edge[1]]['pos']
edge_trace['x'] += tuple([x0, x1, None])
edge_trace['y'] += tuple([y0, y1, None])
#Adding nodes to the plot
node_trace = [Link](x=[],y=[],text=[],
mode='markers',hoverinfo='text', marker=dict(
showscale=True,colorscale='RdBu',reversescale=True,size=15,c
olor=[],colorbar=dict(thickness=10,
title='Node
Connections',xanchor='left',titleside='right'),line=dict(wid
th=0)))
for node in [Link]():
x, y = [Link][node]['pos']
node_trace['x'] += tuple([x])
node_trace['y'] += tuple([y])
Annotations for each node can be created to appear when
someone hovers over them. This can be achieved by using the 'text'
option of 'node_trace'.
In this scenario, the number of connections of each node needs to
be shown. The 'adjacency' method is used to extract the number of
connections between two different nodes. Colour can be added to
each node by using the 'marker' and 'color' options of 'node_trace',
as shown in the code below:
for node, adjacencies in enumerate([Link]()):
node_trace['marker']['color']+=tuple([len(adjacencies[1])])
#print(adjacencies[0])
node_info = adjacencies[0] +' # of connections:
'+str(len(adjacencies[1]))
node_trace['text']+=tuple([node_info])
Finally, a figure is created and 'edge_trace' and 'node_trace' are
plotted using the 'iplot' method, as shown in the code below:
fig = [Link](data=[edge_trace, node_trace],
layout=[Link](title='<br>Concept Network
graph',titlefont=dict(size=16),showlegend=False,hovermode='c
losest',
margin=dict(b=20,l=5,r=5,t=40),annotations=[
dict(text="",showarrow=False,xref="paper", yref="paper") ],
xaxis=dict(showgrid=False, zeroline=False,
showticklabels=False),
yaxis=dict(showgrid=False, zeroline=False,
showticklabels=False)))
#plotting the graph
iplot(fig)
The output of the above code is shown below. Each node
represents different technologies and edges are a connection
between those technologies.
The 'plotly' library is interactive in nature. Hovering over individual
nodes displays the number of connections. For example, in the
graph above, it can be observed that Python has 7 connections.
Note: More the number of connections in the plot, higher is the
value of red.