Reset password New user? Sign up

Existing user? Log in

Already have an account? Log in here.

  • Karleigh Moore
  • Josh Silverman
  • Sam Solomon
  • Blake Farrow
  • Suyeon Khim

There are many systems in the natural world and in society that are amenable to mathematical and computational modeling. However, not everything is easily codified as a system of particles with coordinates and momenta. Some systems and problems such as social networks, ecologies, and genetic regulatory schemes are intrinsically divorced from spacetime descriptions, and instead are more naturally expressed as graphs that reflect their topological properties. At their simplest, graphs are simply collections of nodes – representing some class of objects like people, corporate boards, proteins, or destinations on the globe – and edges, which serve to represent connections like friendships, bridges, or molecular binding interactions.

What is a graph?

Representation of graphs, breadth-first search, depth-first search, contrasting traversals, additional problems.

Consider the highway system of the eastern coast of the United States. A road inspector is given the task of writing reports about the current condition of each highway. What would be the most economical way for him to traverse all the cities? The problem can be modeled as a graph.

In fact, since graphs are dots and lines , they look like road maps. The dots are called vertices or nodes and the lines are called edges. They may have a value assigned to them (weighted) or they may just be a mere indicator of the existence of a path (unweighted). More formally, a graph can be defined as follows:

A graph \(G\) consists of a set of \(V\) of vertices (or nodes ) and a set \(E\) of edges (or arcs ) such that each edge \(e \in E\) is associated with a pair of vertices \(\in V\). A graph \(G\) with vertices \(V\) and edges \(E\) is written as \(G=(V,E)\).

Because graphs are so pervasive, it is useful to define different types of graphs. The following are the most common types of graphs:

Undirected graph: An undirected graph is one in which its edges have no orientations, i.e. no direction is associated with any edge. The edges \((x,y)\) and \((y,x)\) are equivalent.

Directed graph: A directed graph or digraph \(G\) consists of a set \(V\) of vertices (or nodes) and a set of edges (or arcs) such that each edge \(e \in E\) is associated with an ordered pair of vertices. If there is an edge \((x,y)\), it is completely distinct from the edge \((y,x)\).

Undirected graphs are typically represented by a line with no arrows, which implies a bidirectional relationship between node A and node B. Directed graphs use an arrow to show the relationship from A to B.

Directed acyclic graph : A directed acyclic graph (commonly abbreviated as DAG) is a directed graph with no directed cycles. A cycle is any path \(\{A_1, \ldots, A_n\}\) such that the edges \(A_1\rightarrow A_2\), \(A_2\rightarrow A_3\), \(\ldots\), and \(A_n\rightarrow A_1\) all exist, thus forming a loop. A DAG is a graph without a single cycle.

List all the edges and vertices of the undirected graph \(G\) in the figure above. The graph \(G\) consists of the set of vertices \(V\) = {Massachusetts, Maine, Connecticut, New York, Maryland, New Jersey}. Its edges are \(E =\) {(Maine,Massachusetts) , (Massachusetts, Connecticut) , (Connecticut,New York), (New York,Maine), (New York,Massachusetts), (New Jersey, Maine),(Maryland, New York), (Maine, Maryland)}. Note that since the graph is undirected, the order of the tuples in denoting the edges is unimportant. \(_\square\)

Government surveillance agencies have a tendency to accumulate strange new powers during times of panic. The US National Security Agency (NSA) now has the ability to monitor the communications of suspected individuals as well as the communications of people within some number of hops of any suspect. In the communication network above, which person is connected to the greatest number of people through 1 hop or less?

Details and Assumptions:

  • Each dot represents a person.
  • Each line represents communication between the people on either end.
  • If X communicates with Y, and Y communicates with Z, we say that X and Z have a 1-hop connection, and that X has a 0-hop connection with Y.

Above we represented a graph by drawing it. To represent it in a computer, however, we need more formal ways of representing graphs. Here we discuss the two most common ways of representing a graph: the adjacency matrix and the adjacency list.

The adjacency matrix

Represent the graph above using an adjacency matrix. To obtain the adjacency matrix of the graph, we first label the rows and columns with the corresponding ordered vertices. If there exists an edge between two vertices \(i\) and \(j\), then their corresponding cell in the matrix will be assigned \(1\). If there does not exist an edge, then the cell will be assigned the value \(0\). The adjacency matrix for the graph above is thus \[\quad \begin{bmatrix} & a & b & c & d & e\\ a & 0 & 1 & 1 & 0 & 1 \\ b & 1 & 0 & 0 & 0 & 0\\ c & 1 & 0 & 0 & 1 & 1\\ d & 0 & 0 & 1 & 0 & 0\\ e & 1 & 0 & 1 & 0 & 0\\ \end{bmatrix}. \ _\square \quad\]

Adjacency list

An adjacency list representation of a graph is a way of associating each vertex (or node) in the graph with its respective list of neighboring vertices. A common way to do this is to create a Hash table . This table will contain each vertice as a key and the list of adjacent vertices of that vertices as a value.

For our example above, the adjacency list representation will look as follows:

We can see that the adjacency list is much less expensive on memory as the adjacency matrix is very sparse.

Most graph algorithms involve visiting each vertex in \(V\), starting from a root node \(v_0\). There are several ways of achieving this. The two most common traversal algorithms are breadth-first search and depth-first search.

In a breadth-first search , we start with the start node, followed by its adjacent nodes, then all nodes that can be reached by a path from the start node containing two edges, three edges, and so on. Formally the BFS algorithm visits all vertices in a graph \(G\), that are \(k\) edges away from the source vertex \(s\) before visiting any vertex \(k+1\) edges away. This is done until no more vertices are reachable from \(s\). The image below demonstrates exactly how this traversal proceeds:

For a graph \(G = (V,E)\) and a source vertex \(v\), breadth-first search traverses the edges of \(G\) to find all reachable vertices from \(v\). It also computes the shortest distance to any reachable vertex. Any path between two points in a breadth-first search tree corresponds to the shortest path from the root \(v\) to any other node \(s\).

We may think of three types of vertices in BFS as tree verties, those that have been taken of the data structure. fringe vertices, those adjacent to tree vertices but not yet visited, and undiscovered vertices, those that we have not encountered yet. If each visited vertex is connected to the edge that caused it to be added to the data structure, then these edges form a tree.

To search a connected component of a graph systematically, we begin with one vertex on the fringe, all others unseen, and perform the following step until all vertices have been visited: "move one vertex \(x\) from the fringe to the tree, and put any unseen vertices adjacent to \(x\) on the fringe." Graph traversal methods differ in how it is decided which vertex should be moved from the fringe to the tree. For breadth-first search we want to choose the vertex from the fringe that was least recently encountered; this corresponds to using a queue to hold vertices on the fringe.

What is the state of the queue at each iteration of BFS, if it is called from node 'a'? PP The table below shows the contents of the queue as the procedure. BFS visits vertices in the graph above. BFS will visit the same vertices as DFS. In this example all of them. \[\begin{array}{l|r} \textbf{Node Visited} & \textbf{Queue} \\ \hline \text{a} & \text{a} \\ \text{ } & \text{(empty)} \\ \text{b } & \text{b} \\ \text{f } & \text{b f} \\ \text{i} & \text{b f i} \\ \text{ } & \text{f i} \\ \text{c} & \text{f i c} \\ \text{e} & \text{f i c e} \\ \text{ } & \text{ i c e} \\ \text{g } & \text{ i c e g} \\ \text{ } & \text{ c e g} \\ \text{ } & \text{ e g} \\ \text{d } & \text{ e g d} \\ \text{ } & \text{ g d} \\ \text{ } & \text{ d} \\ \text{ } & \text{ (empty)} \\ \text{ h} & \text{ h} \\ \text{ } & \text{ (empty) } \end{array}\]

Depth-first search explores edges out of the most recently discovered vertex \(s\)  that still has unexplored edges leaving it. Once all of ’s edges have been explored, the search “backtracks” to explore edges leaving the vertex from which  was discovered. This process continues until we have discovered all the vertices that are reachable from the original source vertex. If any undiscovered vertices remain, then depth-first search selects one of them as a new source, and it repeats the search from that source. The algorithm repeats this entire process until it has discovered every vertex:

  • Visit a vertex \(s\).
  • Mark \(s\) as visited.
  • Recursively visit each unvisited vertex attached to \(s\).

A recursive implementation of DFS:

A non-recursive implementation of DFS, it delays whether a vertex has been discovered until the vertex has been popped from the stack.

Similar to tree traversal, the code for breadth-first search is slightly different from depth-first search. The most commonly mentioned difference is that BFS uses a queue to store alternative choices instead of a stack. This small change however leads to a classical graph traversal algorithm. Depth-first search goes down a single path until the path leads to the goal or we reach a limit. When a path is completely explored we back track. BFS however explores all paths from the starting location at the same time.

As we increase the size of our graph, the contrast between depth-first and breadth-first search is quite evident. Depth-first search explores the graph by looking for new vertices far away from the start point, taking closer vertices only when dead ends are encountered; breadth-first search completely covers the area close to the starting point, moving farther away only when everything close has been looked at. Again, the order in which the nodes are visited depends largely upon the effects of this ordering on the order in which vertices appear on the adjacency lists.

John lives in the Trees of Ten Houses, and it is a most ideal and idyllic place for him and the other dwellers up in the canopy. They have invested a tremendous amount of time in engineering these houses, and to ensure no house felt isolated from the others, they built a fresh, finely crafted bridge between each and every house!

Unfortunately, the Trees of Ten Houses were not immune to thunderstorms, nor were the bridges well engineered. The night was treacherous, howling with wind and freezing with rain, so the odds for the bridges were not good--each bridge seemed just as likely to survive as to be shattered!

Fortunately, as there were so very many bridges in the Trees of Ten Houses, when John did wake the following morning, he found he was able to make his way to each and every house using only the existing bridges, though round-about routes may have been necessary. As they began rebuilding, John became curious... what were the chances that they'd all be so lucky?

More formally, if \(P\) is the probability that, after the storm, John is able to traverse to each and every house, what is \(\big\lfloor 10^{10} P \big\rfloor?\)

  • The Trees of Ten Houses do, in fact, contain precisely 10 houses.
  • Before the storm, there exists a single bridge between each and every unique pair of houses.
  • The storm destroys each bridge with independent probability \(\frac{1}{2}\).
  • John is allowed to traverse through others' houses to try to reach all of them, but he must only use the surviving bridges to get there. No vine swinging allowed.

Tagged under #ComputerScience as this problem is quite tedious to do without it, though not impossible.

Image credit: http://hdscreen.me/wallpaper/2645876-bridges-fantasy-art-landscapes-mountains.

Problem Loading...

Note Loading...

Set Loading...

Discover 20 Essential Types Of Graphs And Charts And When To Use Them

A guide to the types of graphs and charts by datapine

Table of Contents

1) What Are Graphs And Charts?

2) Charts And Graphs Categories

3) 20 Different Types Of Graphs And Charts

4) How To Choose The Right Chart Type

Data and statistics are all around us. It is very likely that you have found yourself looking at a chart or graph at work, in the news, sports, media, advertising, and many other places at some point in your life. That is because graphical representations of data make it easier to convey important information to different audiences. That said, there is still a lack of charting literacy due to the wide range of visuals available to us and the misuse of statistics . In many cases, even the chart designers are not picking the right visuals to convey the information in the correct way. 

So, how do you make sure you are using and understanding graphs and charts in the right way? In this post, we will provide you with the necessary knowledge to recognize the top 20 most commonly used types of charts and graphs and give insights into when and how to use them correctly. Each type of chart will have a visual example generated with datapine’s professional dashboard software . 

This knowledge will be valuable if you are a data visualization designer, a business user looking to incorporate visual analytics into his/her work, or just an average viewer looking to learn more about the topic. Let’s start this journey by looking at a definition. 

What Are Graphs And Charts?

A graph or chart is a graphical representation of qualitative or quantitative data. It uses different symbols such as bars, lines, columns, tables, box plots, maps, and more, to give meaning to the information, making it easier to understand than raw data. 

As you probably already know, multiple kinds of graphs and charts are widely used in various fields and industries such as business decision-making or research studies. These visual tools are used to find relationships between different data sets and extract valuable conclusions from them. In some cases, they are built by hand, and in others, most commonly, they are built using visualization tools. 

That said, the type of chart or graph you use will vary depending on the aim of the analysis. For instance, percentages are better viewed through a pie or bar chart while data that is changing over time is better viewed over a line chart. For that reason, it is important to have a clear understanding of the different chart types to make sure you are using the right one. 

Below we will discuss the graph and chart categories. These categories will build a solid foundation that will help you pick the right visual for your analytical aims. Let’s dive into them. 

Charts And Graphs Categories

As mentioned, asking the right questions will form the foundations for choosing the right types of visualization graphs for your project, strategy, or business goals. The fundamental categories that differentiate these questions are based on:

  • Relationship : Understanding connections between different data points can significantly help discover new relevant insights. For instance, in the medical field, analyzing relationships between diseases and gene interactions can help discover a treatment for a particular disease. When it comes to visuals, a few graphics can help you easily identify and represent relationships. Scatter plots are valuable when you want to represent smaller data sets of two variables while bubble graphs are best for larger information with three or more variables. 
  • Distribution: In statistics, distribution refers to the possibility of the occurrence of an outcome. To understand this, scientists and analysts use charts to represent the frequency distribution of the data and extract conclusions from it. For this purpose, they use line charts to analyze trends, scatter plots to highlight similarities across variables, and histograms to see the frequency distribution of a single variable across categories. 
  • Composition : The purpose of business graphs and charts for composition is to compare parts to a whole in absolute numbers and normalized forms, usually a percentage. It is one of the most common and traditionally used visualization categories and it is usually limited by the simplicity of the chart types. Common composition graphs include pies, tree maps, and stacked bar charts. 
  • Comparison: As its name suggests, this category refers to the comparison of multiple variables or multiple categories within a single variable. When comparing information it is fundamental to pick a chart that will make it easier to understand the differences. These differences can be within multiple elements, for example, top-selling products, or over time, such as the development of sales for different products over a year. For this purpose, tables, spiders, lines, columns, or area graphs are always a good choice.

To get a clearer impression, here is a visual overview of which chart to select based on what kind of data you need to show:

Overview to use the right data visualization types for comparisons, compositions, relationships and distributions.

**click to enlarge**

Discover 20 Different Types Of Graphs And Charts

Now that you understand the key charting categories you are ready to dive into the main types of graphs and when to use them. Here, we will focus on the 20 most common types of visuals to represent your data in the most meaningful way possible. Each chart type has a visual example generated with datapine .

1) Number Chart

Sales graphs example as number chart with trend: Amount of Sales Year to Date vs Last Period

When to use 

A real-time number chart is essentially a ticker that will give you an immediate overview of a particular KPI . At a glance, you can see any total such as sales, percentage of evolution, number of visitors, etc. This is probably the easiest visualization type to build with the only consideration being the period you want to track. Do you want to show an entire history or simply the latest quarter? It is crucial to label the period clearly so your audience understands what story you are telling. Adding a trend indicator compares your number to the previous period (or to a fixed goal, depending on what you are tracking).

Other considerations

Number charts are often the first thing people see and are the quickest to read, so if there are too many, your narrative can get diluted. Using too many can also make your dashboard a little superficial. If you want more in-depth information, limit the number of number graphs and leave room for other types of data visualization that drill down a little deeper.

When you add a trend indicator, we suggest you compare numbers from the same period. For example, if you are tracking total sales for the current quarter, compare that data to the same quarter last year (or last period – depending on your story). If you select a target manually (perhaps you have no accurate past data), be sure to set realistic goals to be able to get on top of your KPI management practice. Again, remember to label the trend indicator clearly so your audience knows exactly what they are looking at.

2) Line Chart

Sales graph in the form of line chart: amount of revenue by payment method

The purpose of a line chart is to show trends, accelerations (or decelerations), and volatility. They display relationships in how data changes over a period of time. In our example above, we are showing Revenue by Payment Method for all of 2019 . Right away, you can see that the credit card payments were the highest and that everything took a dip in September. The takeaways are quick to register yet have depth.

Too many lines (variables) can make your chart complicated and hard to decipher. You may also find your audience constantly referencing the legend to remind them which one they are looking at. If you have too many variables, it’s time to consider a second (or even third) chart to tell this story.

When it comes to layout, keep your numbers relevant. When you set up your axis scale, keep it close to the highest data point. For example, if we had set the y-axis above to track all the way to 200K (when our highest data point is just over 90K), our chart would have been squished and hard to read. The top half would have been wasted space, and the data crammed. Let your data breathe a little!

One more thing!

A great feature of line graphs is that you can combine them with other types of visualizations, such as bar graphs. Using a double y-axis, one for the bar graph and one for the line, allows you to show two elements of your story in one graph. The primary y-axis below shows orders (bar graph), and the secondary y-axis is sales totals (line). The metrics are different and useful independently, but together, they tell a compelling story.

Two data visualization types combined: line chart and column chart

Maps are great at visualizing your geographic data by location. The information on a map is often displayed in a colored area map (like above) or a bubble map. Because maps are so effective at telling a story, they are used by governments, media, NGOs, nonprofits, public health departments – the list goes on. Maps aren’t just for displaying data; they also direct action. This was seen most recently through the Zika outbreak. Mapping the spread of the disease has helped health officials track it and effectively distribute resources where they are most needed.

Even if you aren’t saving the world from Zika, maps can help! For example, they are great at comparing your organization’s sales in different regions.

Everyone loves maps. However, that doesn’t mean you always need to display one. If the location isn’t a necessary part of your analytics story, you don’t need a map. They take up a lot of room, so only use them when necessary. Also, don’t just fill your maps with data points. Clickhole did a good job of satirizing this common data visualization type by placing 700 red dots on a map. Filling your map with data points doesn’t tell a compelling story; it just overwhelms the audience.

4) Waterfall Chart

One of the best charts example: waterfall chart

This extremely useful chart depicts the power of visualizing data in a static, yet informative manner. It shows the composition of data over a set time period, illustrating the positive or negative values that help in understanding the overall cumulative effect. The decrements and increments can cause the cumulative to fall below or above the axis at various points, causing a clear overview of how the initial value is affected. It is often used in financial departments for analytical purposes, usually depicting the changes in revenue or profit. For example, your MRR ( monthly recurring revenue ), new revenue, upsell, lost, and current revenue. In our example above, we can conclude that our current revenue increased in our set time period.

Waterfall charts are static in their presentation so if you need to show dynamic data sets, then stacked graphs would be a better choice. Also, showing the relationship between selected multiple variables is not optimal for waterfall charts (also known as Cascade charts), as bubble plots or scatter plots would be a more effective solution.

5) Bar Graphs

There are three key types of bar graphs that we will cover in this section: Horizontal, Grouped and Stacked. Although all are in the same chart family, each serves a distinct purpose. Let’s discuss each of them in detail below. 

a) Horizontal Bar Graphs

A data chart in the form of a bar chart: top 5 products on sales

Horizontal charts are perfect for comparative ranking, like a top-five list. They are also useful if your data labels are really long or complex. Keep them in an order that makes sense, though. Either list by value (like we did above) or, if that’s not the strength, choose a logic for the labels that makes sense, like listing them alphabetically.

Because time is best expressed left to right, it’s better to leave showing an evolution for the column chart. Also, like many charts, when you have too many values, a horizontal bar graph quickly becomes cluttered.

b) Grouped bar graph

Grouped bar chart example: total & solved tickets by channel

When to Use 

Grouped bar charts follow the same logic as horizontal bars, except that they show values for two variables instead of one. The two variables are often displayed in disparate colors to help differentiate them from each other. It is recommended to use this chart type when you want to compare elements within a specific category or across other categories on the chart. For instance, in our example generated with a customer service analytics tool, we can see customer service tickets by channel divided between the total and solved ones. In this case, the grouped chart can help compare the values between the total and unsolved tickets as well as compare the number of solved tickets across channels and extract conclusions.  

Just like with the horizontal one, you need to be careful not to add too many categories into this graph type as they can make it look cluttered. The chart becomes difficult to read with the increase in categories, therefore, it is not the best when it comes to relationship or distribution analysis. 

c) Stacked bar chart

Role level by gender as an example of a stacked bar chart

When to Use

A stacked bar chart is a variation of the traditional bar graph but, instead of dealing with one categorical variable, it deals with two or more. Each bar is divided into multiple subcategories that are compared with each other usually using a percentage. In the example above, the chart is comparing management and non-management positions (first categorical variable) that are being occupied by female and diverse employees vs male employees (second categorical variable). This allows the users of the bar to not only focus on the comparisons between the bars themselves but also extract conclusions based on the subcategories from each individual bar. 

When building a successful stacked bar graph it is important to carefully decide which of the two categorical variables will be the primary one. The primary one is the most important one and it will define the overall bar lengths. The secondary one will define the subcategories. Usually, if you are dealing with time ranges or numerical values, these make the best primary variables. However, it will vary from case to case. 

6) Column Graphs

Accounts payable turnover ratio as an example of a column graph

When to use

Column charts are the standard for showing chronological data, such as growth over specific periods, and for comparing data across categories  (you can see this in the example where the accounts payable turnover is being compared based on date ranges). In general, for these kinds of charts, the categories are typically displayed on the horizontal axis while the numerical values are displayed vertically using rectangular columns. The size of the columns is proportional to the values displayed on the chart and their height allows people to easily extract conclusions at a glance. Unlike the bar chart which can display larger or more complex datasets, the column chart has a size limitation making it best to display smaller data. This makes it the go-to visualization for anyone looking for an easy and understandable way to display their information. 

Aside from the obvious design mistakes like using too many colors or too many categories, other things you want to make sure of are: if there is no natural order for the data (e.g. age categories or time ranges), it is recommended to order the values from higher to lowest or lowest to highest. Additionally, the y-axis should always start at 0, otherwise, the height of the columns can become misleading.  

c) Grouped column chart 

Column graphs example: amount of sales by country and channel

Just like the grouped bar chart, the grouped column chart compares two categorical variables instead of one using vertical columns instead of horizontal bars. The purpose of this graph is to see how the subcategories from the secondary variable change within each subcategory of the primary variable. Comparisons can be done within-group or between groups depending on the aim of the analysis.  In our sales data analysis example, Amount of Sales per Channel and Country (last year) , it is clear that we are comparing six regions and five channels. The color coding keeps the audience clued into which region we are referencing, and the proper spacing shows the channels (good design is at the heart of it all!). At a glance, you can see that SEM was the highest-earning channel, and with a little effort, the Netherlands stands out as the region that likely enjoyed the highest sales.

An important consideration when it comes to this graphic is to not use it to compare totals within the different levels of the categorical values. For this purpose, it is better to use a stacked column chart which we will discuss below.  

b) Stacked Column Chart

Stacked column chart: age of new customer by quarter

Stacked charts handle part-to-whole relationships. This is when you are comparing data to itself rather than seeing a total – often in the form of percentages. In the example above, the story isn’t about the total number of customers aged 15-25, but that 22% of the customers were 15-25 in the first quarter of 2014 (and 26% in Q4). The numbers we are working with are relative only to our total.

When showing single part-to-whole relationships, pie charts are the simplest way to go. Twenty-two percent of our customers are 15-25, leaving the other 78% to fit into the pie somehow. People get pie charts. They’re easy. But what if we want to show the same information over different periods? This would be a multiple part-to-whole relationship, and for this, we use a stacked bar graph. Again, we are telling the story of the percentage of customers in a certain age range, per quarter . The total number of each isn’t relevant here (although that information is used in the calculations). With proper spacing, we see each quarter clearly, and the color coding shows that overall, 46-55-year-olds are the most difficult customers to attract.

Aesthetically speaking, when you have too much data, columns become very thin and ugly. This also leaves little room to properly label your chart. Imagine we had 10 different age ranges per column. Some results, if not most, would be only slivers. To make your chart easy to understand, use good colors, proper spacing, and a balanced layout. This invites people to look at your chart and even enjoy it. A pretty chart is a much nicer way to consume data than squinting at a table.

7) Pie Charts

Pie chart example used to show the proportional composition of a particular variable – here number of sales by  product category

The much-maligned pie chart has had a bad couple of years. In fact, it has become pretty cliché to talk about how bad pie charts are. We understand the pie chart doesn’t do a lot, but it does do some things quite well. Pie charts are useful when demonstrating the proportional composition of a particular variable over a static timeframe. Let’s look at some particular cases:

  • When the parts add up to 100%: The “part-to-whole relationship” is built right into it a pie chart in an obvious way. At a glance, any user knows a pie chart is splitting a population into parts and that the total of those parts equals 100%.
  • When approximating is okay: The pie chart is particularly effective when eyeballing values are enough to get the conversation going. Also, it’s easier to estimate the percentage value of a pie chart compared to, let’s say, a bar chart. That’s because pies have an invisible scale with 25%, 50%, 75%, and 100% built-in at four points of the circle. Our eyes can easily decipher these proportions, driving the conversation about what variables do and don’t take up most of the pie. Your audience doesn’t have to guess the proportions – you can easily add data labels or build the sister of the pie chart, the donut chart, to display additional information.
  • When there aren’t many proportions to the variable or they are combined: Pie charts are great when answering questions like, “What two largest suppliers control 65% of the market?”

Your audience isn’t always going to be comprised of data scientists. Accordingly, your presentation should be tailored to your particular audience. This brings us to another pie chart strength: people are familiar with pie charts. Any audience member will feel comfortable interpreting what the pie chart is presenting. As a bonus, circles generate more positive emotions: our brains like to look at circles over sharp corners. In the end, a pie chart simplifies the data story and encourages the audience.

Data visualization guru Edward Tufte famously declared that “pie charts are bad, and the only thing worse than one pie chart is lots of them.” We already talked about the pros of pie charts and why we don’t adhere to this strict no-pie-chart philosophy. We should also state that there are plenty of instances where you should not use a pie chart. First off, pie charts portray a stagnate time frame, so trending data is off the table with this visualization method. Make sure your audience understands the timeframe portrayed and try to document or label this applied filter somewhere.

Pie charts are also not the best types of data charts to make precise comparisons. This is especially true when there are multiple small pieces to the pie. If you need to see that one slice is 1% larger than another, it’s better to go with a bar chart. Another thing about multiple pieces to your pie – you don’t want too many. Pie charts are most effective when just displaying two portions. They lose presentation value after six segments. After six, it is hard for the eyes to decipher the slice's proportion. It also becomes difficult to label the pie chart, and valuable online dashboard /reporting real estate is often wasted in the process.

This brings us to the last issue: circles take up space. If you are using multiple pie charts in a dashboard, it is probably best to combine the data in one chart. We recommend checking out the stacked bar chart for these cases. You can also have a look at the different pie charts that are commonly used and explore the disadvantages of pie charts .

8) Gauge Charts

Illustration of a gauge chart or speedometer chart, a data visualization type used to display a single value

Gauge charts , also known as dial charts or speedometer charts, use needles and colors to show data similar to reading on a dial/speedometer, and they provide an easily digested visual. They are great for displaying a single value/measure within a quantitative context, such as to the previous period or to a target value. The gauge chart is often used in executive dashboards and reports to display progress against key business indicators. All you need to do is assign minimum and maximum values and define a color range, and the gauge chart will display an immediate trend indication.

Gauge charts are great for KPIs and single data points. After that, they can get a bit messy. With only one data point, you can’t easily compare different variables. You also can’t trend data using gauge charts. All of this makes taking actionable insight from a gauge chart difficult. Furthermore, they take up a lot of space – if your live dashboard has precious real estate, it may not be most efficient to fill it with multiple gauge charts. Using one chart to summarize multiple KPIs, you will likely get more bang for your buck.

9) Scatter Plot

A data visualization graph in the form of a scatter plot: average basket size by age

Scatter plot is not only fun to say – it’s what you need when looking for the correlation in a large data set. The data sets need to be in pairs with a dependent variable and an independent variable. The dependent (the one the other relies on) becomes the y-axis, and the independent – the x-axis. When the data is distributed on the plot, the results show the correlation to be positive, negative (each to varying degrees), or nonexistent. Adding a trend line will help show the correlation and how statistically significant it is.

Scatter plots only work when you have a lot of data points and a correlation. If you are only talking about a few pieces of information, a scatter plot will be empty and pointless. The value comes through only when there are enough data points to see clear results. If you only have a little data or if your scatter plot shows no correlation at all, this chart has no place on your business dashboard. 

10) Spider Chart

A spider chart example with 3 variables: products sold, category and country

Spider charts, or radar charts, are comparative charts used when multivariate data is displayed with three or more quantitative variables (aspects). This is useful when you want to evaluate two or more “things” using more than three aspects, all of which are similarly quantifiable. It’s certainly a mouthful, but it’s simple when you put it into use. Spider charts are great for rankings, appraisals, and reviews. For example, the three “things” we are comparing in our e-commerce example above are regions: Australia, Europe, and North America. The aspects we are comparing against are products sold are Cameras, TVs, Cell Phones, Games, and Computers. Each variable is being compared by how many units were sold – between 0 and 500. Europe is clearly outselling in all areas, and Australia is particularly weak in Cameras and Cell Phones. The concentration of strengths and weaknesses is evident at a glance.

This is not the easiest data analysis chart to pull off, but it really impresses when done correctly. Using this chart if you have more than five values in your dimension (five “things” to evaluate) makes it hard to read, which can make it pointless altogether. Whether you use solid lines or shaded areas, too many layers are difficult to interpret. Naturally, it is not a choice when you want to show time (the whole circular thing...).

Illustration of a table chart

We know – tables aren’t technically a graph. But sometimes, you really just need a table to portray your data in its raw format. With a table, you can display a large number of precise measures and dimensions. You can easily look up or compare individual values while also displaying grand totals. This is particularly beneficial when your audience needs to know the underlying data or get into the “weeds.” Tables are also effective if you have a diverse audience where each person wants to look at their own piece of the table. They are also great at portraying a lot of text or string values.

Remember – just because you are using a table doesn’t mean it can’t be visually pleasing. You can use various colors, border styles, font types, number formats, and icons to highlight and present your data effectively.

There are many reasons to use a table, but there are also many instances where different types of charts are a better choice. It all comes down to our eyes and brain. Tables interact primarily with the verbal system – we read tables. This reading includes processing the displayed information in a sequential fashion. Users read down columns or across rows of numbers, comparing one number to another. The keywords here are reading, processing, and time. Tables take longer to digest.

Graphs, on the other hand, are perceived by our visual system. They give numbers shape and form and tell a data story. They can present an immense amount of data quickly and in an easy-to-consume fashion. If data visualization is needed to identify patterns and relationships, a table is not the best choice. Also, while it is fun to get creative with colors, formatting, and icons, make sure your formatting and presentation choices are increasing your perception. The tables are hard enough to read as is!

12) Area Charts

a stunning area chart showing number of sales by payment method

The area chart is closely related to the line chart. Both chart types depict a time-series relationship, show continuity across a dataset, and are good for seeing trends rather than individual values. That said, there are some key differences between the two. Because of these differences, “when to use area charts” does not equal “when to use line charts.”

Line charts connect discrete but continuous data points through straight line segments. This makes them effective for facilitating trend analyses. Area charts technically do the same, except that the area below the plotted lines is filled with color. In this case, an un-stacked area chart is the same thing as a line chart – just with more coloring. The problem you run into here is occlusion: when you start comparing multiple variables/categories in an unstacked area chart, the upper layers obscure the lower layers. You can play around with transparency, but after three variables, un-stacked area charts are hard to read.

This brings us to the most commonly used area chart: the stacked area chart. Like stacked bar charts, stacked area charts portray a part-to-whole relationship. The total vertical of a stacked area chart shows the whole, while the height of each different dataset shows the parts. For example, a stacked area chart can show the sales trends for each region and the total sales trend. There are two different stacked area chart types you can use to portray the part-to-whole relationship.

Traditional Stacked Area Chart: The raw values are stacked, showing how the whole changes over time.

Stacked Percentage Area Chart: Percentages are stacked to show how the relationship between the different parts changes over time. This is best used to show the distribution of categories as parts of a whole where the cumulative total is less important.

As we hinted earlier, for the most part, you should stay away from un-stacked area charts. If you are just comparing 2-3 different variables that don’t obscure each other, then go ahead. But in general, they are often messy and don’t follow data visualization and dashboard design best practices . When it comes to stacked area charts, don’t use them when you don’t need to portray a part-to-whole relationship – use a line graph instead. Also, if you are trying to compare 7+ series, a stacked area graph becomes hard to read. In this case, you should once again turn to the line graph.

13) Bubble Plots

Bubble plot is one of the types of data visualization that is useful for visualizing more variables with multiple dimensions

Bubble charts, or bubble graphs, are among the best types of data graphs for comparing several values or sets of data at a glance. If you’re looking to show the relationship between different product categories, revenue streams, investment risks, costs, or anything similar, bubble charts or plots are incredibly effective.

For instance, our example bubble plot showcases the relationship between a mix of retail product categories, primarily the number of orders and profit margin.

Here, you can tell that the TV & Home Theater product category has the highest number of orders (around 3,000 as you can see from the number scale on the left) as well as the highest profit margin, and therefore, it is the biggest bubble on the chart. Comparatively, the camera category shows the lowest number of orders in addition to the smallest profit margin and naturally is the smallest bubble on the chart.

The bubble plot is extremely powerful for visualizing two or more variables with multiple dimensions. And here, the bigger the bubble, the higher the profit margin. Not only are bubble plots visually stimulating, but they are also incredibly effective when building a comparative narrative for a specific audience.

It's difficult to go too far wrong with bubble charts, but the most common mistake with these types of business charts is focusing on varying the “radius” of the values rather than the “area” they take up on the chart. Doing so sometimes makes the bubbles on the plot disproportionate to the graph, making the information misleading at a glance. In short, your bubbles should be accurate in terms of size compared to the values. Get this right, and you’ll get the results you deserve. 

14) Boxplot 

Box plot example displaying the patient room turnover by department

Just like the histogram, the box plot is a graph that is used to represent the distribution of numeric data using boxes and lines. Each box is composed of five elements also known as the “Five-number summary” which are the minimum, first quartile, median (second quartile), third quartile, and maximum. Each of these elements represents a value and how it is distributed within the data set. Anything outside these values would be considered an outlier. An outlier is any value that is extremely high or extremely low compared to the nearest data point. Outliers (which are usually plotted as dots in the chart) need to be identified because they can affect the end result of the analysis and box plots are the best visuals to do so.  

Just like other types of charts on this list, box plots are not the best choice when it comes to big data sets. Their visual simplicity makes it hard to see details about the distribution results which makes it more difficult to interpret, especially when dealing with complex data. Plus, this chart works at its best when comparing different groups (as seen in our example above). So, if you are trying to look at the distribution of one single group a histogram is a better choice. 

15) Funnel chart 

Funnel chart example used to show how data moves through a sales pipeline

As its name suggests, a funnel chart is a visualization type used to show how data moves or flows through a specific process. They are commonly utilized to display sales, recruitment, or order fulfillment funnels where the values are often decreasing as the funnel becomes smaller. This can be seen in the example above in which the number of potential clients decreases at each stage of the sales funnel. This is a natural progression that happens because not every person that shows interest in the opportunities stage will end up buying the product or subscribing to the service. 

In some cases, the sizes of the sections of the funnel chart are plotted proportionately with the value they are representing. This means the top section is 100% and the rest will represent their corresponding percentage with their size. This is not the case with our example in which the sections are sized to match the funnel shape, not the values contained in each section. 

Funnel graphics are very specific visuals that can only be used in particular cases. You should only use it if your data goes through a sequence of stages and the values are decreasing with each stage. Plus, they are only useful to represent a single variable which means they cannot be used to visualize relationships between variables. A good alternative for a funnel graph is a bar or column chart. 

16) Bullet chart 

Example of a bullet chart

A bullet chart is a variation of a bar or column chart but it provides some extra visual elements to give more context to the data. It is usually used for performance tracking to make comparisons against a goal or other relevant values and it is composed of three key elements. A single measure is represented by a darker shade bar with a length that represents the performance of that value, qualitative ranges are represented by lighter shades in the background, and a target or comparative measure which is represented with a small line that is perpendicular to the orientation of the graph. Bullet charts are great alternatives to gauge charts, especially when you are working with a KPI dashboard and don’t want to take up too much space from it. 

It is important to note that bullet charts are complex visuals that might be challenging to understand for non-technical audiences. In some cases, some people might choose to remove the shaded background to focus only on the actual value against the target or remove the target and focus on the qualitative ranges to make the chart friendlier to analyze.    This variation is also known as an overlapping bullet chart and it can be done using columns and bars, as we will see in our two examples below.

1. Overlapping bars bullet chart 

Overlapping column bullet chart example tracking the number of orders by product category

As we saw with different graph types previously, the bullet chart can be vertical (using columns) or horizontal (using bars). It is recommended to use bars when you want to display more categories or longer category names to avoid making the visual cluttered. In the example above, we can see the number of orders by product of the current year compared to a target. In this case, due to the number of products, a bar bullet graph is the best choice as it contains a lot of information without affecting the readability of the data.

2. Overlapping columns bullet chart 

Overlapping bars bullet chart example tracking the number of orders by product category

On the other side, a bullet column chart is a better choice when you want to organize categories from left to right or when you have fewer categories to show. In this case, we can see the number of orders by product category. Given that product categories are fewer than the actual number of products, it is a good choice to pick columns to represent this data. In a traditional bullet chart, the number of orders by a quarter could be added for additional context as qualitative measures.

17) Treemap chart 

Treemap chart example displaying the patient drug cost per stay by department

A treemap is a chart type used to display hierarchical data through rectangles that decrease their size as the value decreases, this process is also referred to as nesting. It is used to display large amounts of raw data in a visually appealing way that allows users to easily extract valuable conclusions at a glance. Its name comes from the shape of a tree, as the chart can be divided into multiple categories with different “branches” and “sub-branches”. Each of these categories should have a different color and the dimensions of the rectangles are based on the size of the data being displayed. 

Given that a treemap is used to visualize massive amounts of raw data, they can display an infinite amount of subcategories (or sub-branches) which can make them harder to understand. However, in most cases, users can drill down into the different categories to dig deeper into the data and answer different questions that might arise. 

If you are not trying to show hierarchical data then you should stay away from treemaps. Just like it happens with pie charts, this visualization is simply showing parts-to-whole relationships, therefore, it becomes useless for other purposes. You should also avoid treemaps if the data being displayed is too close in size. This defeats the purpose of the graph which is to easily identify the largest item from a specific category. A few alternatives for treemaps include column charts and scatter plots.

18) Stream charts 

Example of a stream chart tracking the number of orders by product category

A stream graph is considered a variation of the area chart with the difference that, while the area chart is plotted with a fixed x-axis, the stream graph has values displayed around a central axis. Hence, the flowing river-like shape. They are frequently used to identify trends and patterns in big datasets with multiple categories and evaluate how they change over time. Just like with other kinds of charts on this list, the width and length of the streams are proportional to the values being displayed. The colors can represent different categories or other specific criteria. In our example above, we can see the number of orders by product categories each month. The width of each stream can provide valuable insights into the performance of each category. For instance, from June to August orders for TVs and Home Theaters decreased a lot compared to other months so some conclusions need to be drawn.

In general, if your aim is to use the chart to deeply analyze the data and extract conclusions from it, then the stream is not your best option. They are often cluttered with a lot of information which can lead to legibility issues. This can happen especially when you have smaller categories that end up looking way too small compared to bigger ones. For that reason, it is best to use stream charts as interactive visuals instead of static or printed ones. 

19) Word Cloud 

Different types of charts and graphs examples: word cloud tracking the frequency of citites in customer reviews

A word cloud is a straightforward type of graph that displays a set of words concerning a specific topic. The words are arranged in different directions and the sizes of the words will vary depending on specific criteria. For example, if a word cloud is generated based on a text from product reviews, the size of the words can be influenced by the number of times each word is mentioned within the text. On the other hand, if you are generating a word cloud of all the countries in the world, the names of the countries can be bigger or smaller depending on their population. From an analytical perspective, word clouds don’t provide a lot of value apart from being an engaging and visually appealing way of presenting a topic or supporting discussions. 

There is no general rule when it comes to colors on a word cloud. Some might use different colors to provide meaning to certain words while others might use standard colors to match their branding. Whichever case you are using, the rule of not adding too many colors to avoid overcrowding the visual still applies when it comes to word clouds. 

20) Progress chart 

As its name suggests, this chart is used to track the progress of a specific activity or scenario usually in a percentage form. It can be represented using bars or columns and is often tracked against a set target, as seen in the graph examples below, in which you can see a colored area representing the completed percentage and a lighter shade representing the remaining percentage to complete 100%. Progress graphs are wildly popular when tracking the development of a project as they provide a clear overview of the status of different tasks. They are also valuable visuals when you are trying to show any kind of percentage value or progress against a target. 

Progress charts are very straightforward and don’t provide a lot more information than the development of a metric. If you want to gain more insights you can explore using a bullet chart as they provide more context to the data. 

  • Progress bar graph 

Percentage of purchases in time & budget as a progress bar example

The progress bar chart is used to track the progress of a specific activity or metric using horizontal bars. The example above is tracking the percentage of purchases in time and budget from a procurement department. Ideally, the end goal for each category would be 100% as this means all purchases are made on the expected time and budget. However, this is not always the case and the progress bar is a great way to see how far from the expected target the values actually are. In this case, the average is represented by a darker color of green, and the remaining percentage to reach 100% is represented by a lighter shade.  

  • Progress column graph 

The average time to fill by department as an example of a progress column chart

The progress column chart is a type of progress chart that uses columns to represent different data values. In this case, our example is showing the average time to fill a position by the department where each department has a predefined target they are expected to reach. In this case, the target value is represented by a dark purple dot, in other cases, it could be represented with a lighter shade of the same purple from the column. Using a progress chart to represent this metric is a great way to compare the different departments and see if any of the processes need to be optimized to better reach the expected target. 

How To Choose The Right Chart Type: 9 Essential Questions To Ask

To go further into detail, we have selected the top 9 questions you need to consider to ensure success from the very start of your journey.

1. What story do you want to tell?

At its core, data charts are about taking data and transforming it into actionable insight by using visuals to tell a story. Data-driven storytelling is a powerful force as it takes stats and metrics and puts them into context through a narrative that everyone inside or outside of the organization can understand.

By asking yourself what kind of story you want to tell with your data and what message you want to convey to your audience, you’ll be able to choose the right data visualization types for your project or initiative. And ultimately, you’re likely to enjoy the results you're aiming for.

For more on data storytelling, check out our full guide for dashboard presentation and storytelling.

2. Who do you want to tell it to?

Another key element of choosing the right data visualization types is gaining a clear understanding of who you want to tell your story to – or in other words, asking yourself the question, “ Who is my audience ?”

You may be aiming your data visualization efforts at a particular team within your organization, or you may be trying to communicate a set of trends or predictive insights to a selection of corporate investors. Take the time to research your audience, and you’ll be able to make a more informed decision on which data visualization chart types will make the most tangible connection with the people you’ll be presenting your findings to.

3. How big is your data? 

As you probably learned from our list of the essential types of charts and when to use them, the size of your data will significantly affect the type of visualization you decide to use. Some charts are not meant to be used with massive amounts of data due to design aspects while others are perfect for displaying larger information. 

For example, pie charts are not good if you are trying to show multiple categories. For that purpose, a scatter plot works best. Another example is with column and bar charts. Bar charts use horizontal bars that make it easier to represent larger data sets. On the other side, column charts are limited by size due to their vertical orientation, making them better for smaller data. 

4. What is the type of data you are using? 

Another important question to ask yourself is what type of data you are using. As we saw at the beginning of the post, there are 4 key categories when it comes to data visualization: composition, distribution, relationship, and comparison. There are also qualitative and quantitative data that can be better represented using a particular graphic. For this reason, it is important to carefully define the type of data you are using before thinking about visualizing it. In the following questions, we will see what you need to ask yourself based on the mentioned categories. 

5. Are you looking to analyze particular trends?

Every data visualization project or initiative is slightly different, which means that different data visualization chart types will suit varying goals, aims, or topics.

After gaining a greater level of insight into your audience as well as the type of story you want to tell, you should decide whether you're looking to communicate a particular trend relating to a particular data set, over a predetermined time period. What will work best?

  • Line charts
  • Column charts
  • Area charts

6. Do you want to demonstrate the composition of your data?

If your primary aim is to showcase the composition of your data – in other words, show how individual segments of data make up the whole of something – choosing the right types of data visualizations is crucial in preventing your message from becoming lost or diluted.

In these cases, the most effective types of visual charts include:

  • Waterfall charts
  • Stacked charts
  • Map-based graphs (if your information is geographical)

7. Do you want to compare two or more sets of values?

While most types of data visualizations will allow you to compare two or more trends or data sets, there are certain graphs or charts that will make your message all the more powerful.

If your main goal is to show a direct comparison between two or more sets of information, the best choice would be:

  • Bubble charts
  • Spider charts
  • Columned visualizations
  • Scatter plots

Data visualization is based on painting a picture with your data rather than leaving it sitting static in a spreadsheet or table. Technically, any way you choose to do this count, but as outlined here, there are some charts that are way better at telling a specific story.

8. Is timeline a factor?

By understanding whether the data you’re looking to extract value from is time-based or time-sensitive, you’ll be able to select a graph or chart that will provide you with an instant overview of figures or comparative trends over a specific period.

In these instances, incredibly effective due to their logical, data-centric designs, functionality and features are:

  • Dynamic line charts

9. How do you want to show your KPIs?

It’s important to ask yourself how you want to showcase your key performance indicators as not only will this dictate the success of your analytical activities but it will also determine how clearly your visualizations or data-driven stories resonate with your audience.

Consider what information you’re looking to gain from specific KPIs within your campaigns or activities and how they will resonate with those that you’ll be sharing the information with - if necessary, experiment with different formats until you find the graphs or charts that fit your goals exactly.

Here are two simple bonus questions to help make your data visualization types even more successful:

  • Are you comparing data or demonstrating a relationship?
  • Would you like to demonstrate a trend?

At datapine, data visualization is our forte. We know what it takes to make a good dashboard – and this means crafting a visually compelling and coherent story.

"Visualization gives you answers to questions you didn’t know you had." – Ben Shneiderman

Design-thinking In Data Visualization

When it comes to different data visualization types, there is no substitute for a solid design. If you take the time to understand the reason for your data visualization efforts, the people you’re aiming them at, and the approaches you want to take to tell your story, you will yield great results.

Here at datapine, we’ve developed the very best design options for our dashboard reporting software , making them easy to navigate yet sophisticated enough to handle all your data in a way that matters.

With our advanced dashboard features , including a host of global styling options, we enable you to make your dashboard as appealing as possible to the people being presented with your data.

Your part in creating an effective design for the different types of data charts boils down to choosing the right visualization to tell a coherent, inspiring, and widely accessible story. Rarely will your audience understand how much strategic thought you have put into your selection of dashboards – as with many presentational elements, the design is often undervalued. However, we understand how important this is, and we’re here to lend a helping hand.

In this guide, we covered different types of charts to represent data, explored key questions you need to ask yourself to choose the right ones, and saw examples of graphs to put their value into perspective. By now, you should have a better understanding of how each type of visual works and how you can use them to convey your message correctly. 

To summarize, here are the top types of charts and their uses:

  • Number Chart - gives an immediate overview of a specific value .
  • Line Chart - shows trends and changes in data over a period of time .
  • Maps - visualizes data by geographical location.
  • Waterfall Chart - demonstrates the static composition of data.
  • Bar Graphs - used to compare data of large or more complex items .
  • Column Chart - used to compare data of smaller items. 
  • Gauge Chart - used to display a single value within a quantitative context.
  • Pie Chart - indicates the proportional composition of a variable.
  • Scatter Plot - applied to express relations and distribution of large sets of data.
  • Spider Chart - comparative charts great for rankings, reviews, and appraisals.
  • Tables - show a large number of precise dimensions and measures .
  • Area Chart - portrays a part-to-whole relationship over time .
  • Bubble Plots - visualizes 2 or more variables with multiple dimensions.
  • Boxplot -  shows data distribution within multiple groups.
  • Funnel Chart - to display how data moves through a process.
  • Bullet Chart - comparing the performance of one or more primary measures .
  • Treemap - to plot large volumes of hierarchical data across various categories.
  • Stream Graph - shows trends and patterns over time in large volumes of data.
  • Word Cloud - to observe the frequency of words within a text.  
  • Progress Chart - displays progress against a set target or goal.

But in our hyper-connected digital age, there are many more different kinds of graphs you can use to your advantage. Putting everything together in a professional business dashboard is even better. These visual tools provide centralized access to your most important data to get a 360-view of your performance so you can optimize it and ensure continuous growth.

Complete with stunning visuals, our advanced online data visualization software can make it easy for you to manipulate your data and visualize it using professional dashboards. The best part is, you can try it for a 14-day trial , completely free!

Representing Graphs in Code

David Landup

Graphs in Python can be represented in several different ways. The most notable ones are adjacency matrices, adjacency lists, and lists of edges . In this guide, we'll cover all of them. When implementing graphs, you can switch between these types of representations at your leisure.

First of all, we'll quickly recap graph theory, then explain data structures you can use to represent a graph, and, finally, give you a practical implementation for each representation.

Note: The implementations found in this lesson can be found in the following GitHub repo .

What Is a Graph - In Short

Let's quickly skim over basic definitions regarding graphs once again. A graph is a data structure you can use to model hierarchy and relationships between objects. It consists of a set of nodes and a set of edges . Nodes represent individual objects, while edges illustrate relationships between those objects.

Note: Again, the terms 'node' and 'vertex' ('nodes' and 'vertices') are often used interchangeably. In this course, we've opted to use the term node , but it has the same meaning as the term vertex .

If every edge in a graph illustrates a two-way connection, we call that graph undirected . On the other hand, if you can traverse each edge in only one direction, the graph is directed .

types of graph representation

Not all nodes of a graph need to be connected with others. If you can access each node from any other node in a graph - we call that graph connected . But sometimes there are some nodes you can't access from any other node in a graph - that's what disconnected graphs are all about. The common misconception is that every graph has to be connected, but the reality of the matter is that it doesn't - in fact, a graph can contain no edges, just nodes:

types of graph representation

From the implementation standpoint, the one last thing we need to cover is the weight of an edge . It is a numeric value assigned to the edge describing how much it costs to traverse that edge. The smaller the weight of an edge, the cheaper it is to traverse it. Based on that, graphs with weights assigned to their edges are called weighted graphs :

types of graph representation

Armed with the fundamental knowledge, you can dive deeper into ways to implement a graph!

Three Most Common Ways to Represent a Graph

In this section, we'll go over the most common ways you can represent a graph. We'll explain the intuition behind each of them and give you some illustrative examples. Afterward, you can use that knowledge to implement a graph in Python.

Generally speaking, nodes of any given graph are labeled by numbers (starting from zero) for the sake of the simpler implementation. That's why we'll be using that notation in the following examples and implementations.

We'll use the following weighted directed graph as the example in the following sections:

types of graph representation

Note: We've chosen a weighted directed graph as the example because it illustrates most of the implementation nuances. Generally speaking, switching between weighted and unweighted graphs is pretty straight-forward. Switching between directed and undirected graphs is also a pretty easy thing to do. We'll cover each of those topics in the following sections when needed.

List of Edges

A list of edges is probably the simplest way to represent a graph , but since it lacks a proper structure, it is often used just for illustrative purposes. We'll use it to explain some graph algorithms because it provides little to no overhead and allows us to focus on the algorithm implementation, rather than the implementation of the graph itself.

As you already know, each edge connects two nodes and may have a weight assigned to it. Therefore, each edge is represented by a list in the following way: [node1, node2, weight] , where weight is an optional property (not required if you have an unweighted graph). As its name suggests, a list of edges stores a graph as a list of edges represented in the described way.

Let's take a look at one directed weighted graph and its list of edges:

types of graph representation

As you can see, a list of edges is effectively a table. Each row of that table represents one edge - two of its nodes and the weight of that edge. Since this is a weighted graph, the order of nodes in the edge representation illustrates the direction of the edge. You can traverse the edge only from node1 to node2 .

On the other hand, you have two approaches for dealing with undirected graphs . The first approach is to add two rows for each node - one for each edge direction. That approach is space-inefficient, but you must use it if you are using both directed and undirected graphs interchangeably. The second approach can be used only if you are certain that you will deal only with undirected graphs. In that case, you can consider each edge to be undirected and keep the representation the same - one row for each edge.

  • Simple and easy to understand
  • Great for illustrative purposes
  • Represents a graph per definition (a set of nodes and set of edges)
  • Not structured in any shape or form
  • Not eligible for any real-world application
  • Not efficient
  • Not versatile enough to represent both directed and undirected graphs interchangeably

Adjacency Matrix

An adjacency matrix is one of the most popular ways to represent a graph because it's the easiest one to understand and implement and works reasonably well for many applications. It uses an nxn matrix to represent a graph ( n is the number of nodes in a graph). In other words, the number of rows and columns is equal to the number of nodes in a graph.

Initially, every field of the matrix is set to a special value you choose- inf , 0 , -1 , False , etc., suggesting that there are no nodes present in the graph. After the initial stage, you can add every edge of the graph by filling up the appropriate field by 1 (for unweighted graphs) or the edge weight (for weighted graphs).

The mentioned matrix is essentially a table with each row and column representing one node of the graph. For example, row 3 refers to node 3 - that's why you can use an adjacency matrix to represent only graphs with number labeled nodes.

Note: In fact, you can alter the implementation of an adjacency matrix so it can handle differently named nodes, but the additional work needed usually annuls the potential gains. That's why we've opted to use the simpler implementation - only number labeled nodes.

The field which is the intersection of row i and column j refers to a presence or a weight of the edge between nodes i and j . For example, if you fill-up the field which is the intersections of row 1 and column 4 , it indicates that there is the edge connecting nodes 1 and 4 (in that specific order). If a graph is weighted, you fill up that field with the weight of the edge or 1 in a case of an unweighted graph.

In the case of undirected graphs , you must add two entries for each edge - one for each direction.

If the previous explanation wasn't clear enough, let's try to simplify it by showing how to create an adjacency matrix on the example of the following graph:

types of graph representation

There are n nodes in this graph. Therefore, we've created a table with n rows and columns and initialized all cells with 0 - the special value indicating that there are no edges between any two nodes. Since the example graph is weighted and directed, you need to:

  • Scan every edge in a graph
  • Determine the start and the end node of that edge
  • Determine the weight of that edge
  • Fill up the appropriate field of the matrix with the weight value

Let's use the edge 4-3 as an example. The start node is 4 and the end node is 3 , therefore you know that you need to fill up the field that is the intersection of row 4 and column 3 . From the image, you can read that the weight of the edge is 11 , therefore you fill-up the appropriate field with 11 . Now you've marked the presence of the edge 4-3 . That process is repeated until you've marked every edge in a graph.

  • Low lookup time - you can determine whether an edge exists in the time of O(1)
  • Adding/removing edges takes O(1) time
  • Easy to implement and understand
  • Takes more space O(num_of_nodes²)
  • Adding node takes O(num_of_nodes²) time
  • Costly to find adjacent nodes of the selected node - O(num_of_nodes)
  • Costly to traverse a graph - O(num_of_nodes²)
  • Costly to label/enumerate edges - O(num_of_nodes²)

Adjacency List

An adjacency list is the most efficient way to store a graph. It allows you to store only edges that are present in a graph, which is the opposite of an adjacency matrix, which explicitly stores all possible edges - both existent and non-existent. An adjacency matrix is initially developed to represent only unweighted graphs, but in the most effective way possible - using only one array.

As you can see in the illustration below, we can represent our example graph using just an array of 12 integer values. Compare that to the adjacency matrix - it consists of n² elements ( n is the number of nodes in a graph), where the adjacency list takes only n+e elements ( e is the number of edges). Much more space-efficient if a graph is not dense (has a small number of edges).

The problem is that an adjacency list is harder to understand compared to the adjacency matrix, so if you haven't interpreted them before, follow along carefully:

types of graph representation

The first thing you need to know to construct an adjacency list is the number of nodes in a graph. In our example graph, there are 5 nodes, so the first 5 places in a list represent those nodes - e.g. element with the index 1 represents a node 1 . After reserving the first 5 places in a list, you can start filling up the list. The value on the index i refers to the index in the list where you can find indices of adjacent nodes to the node i .

For example, the value on the index 0 is 5 , which means that you should look at the index 5 in the adjacency list to find which nodes are connected to node 0 - those are nodes 0 , 1 , and 2 . But how did we know when to stop looking for adjacent nodes? It's pretty simple! Take a look at the value on the index next to 0 in the list. The next index is 1 , it represents node 1 , and its value is 8 , meaning that you can find nodes adjacent to node 1 starting from index 8 in the adjacency list. Therefore, you can find nodes adjacent to node 0 as values of the list between indices 5 and 8 .

To understand this structure more readily, you can reorder elements of the adjacency list in a more structured way. If you do that, you can see that the resulting structure looks a lot like a linked list:

types of graph representation

Furthermore, the structure of the linked list resembles a lot on dictionaries (or maps). It has a set of keys - nodes, and a set of values for each key - a set of nodes adjacent to the key node. If you want to represent a weighted graph, you must find a way to store weight besides the adjacent node (as you can see in the following illustration). But we'll cover implementation details in later sections.

The following illustration shows you the adjacency list of the example graph - both with and without weights:

types of graph representation

When you take a look at the weighted adjacent list, you can easily construct the set of edges of the example graph. Node 0 has three adjacent nodes - 0 , 1 , 2 , meaning that graph has edges 0-0 , 0-1 , and 0-2 . The weight of those edges can also be read from the adjacency list. The weight of edge 0-0 is 25 , the weight of edge 0-1 is 5 , and so on, for every edge in the graph.

  • Cheap to find adjacent nodes of the selected node - O(1)
  • Efficient for less dense graphs (low number of edges compared to the number of nodes)
  • You can use it for both letter and number labeled nodes
  • Low cost of traversing a graph - O(length_of_list)
  • Low cost of labeling/enumerating edges - O(length_of_list)
  • High lookup time - O(length_of_list)
  • High cost of removing an edge - O(length_of_list) (logical extension of high lookup time)

Note: The length_of_list is equal to the sum of the number of nodes and number of edges in a graph.

How to Implement a Graph in Python

Now you know how to represent a graph with the most common data structures! The next thing to do is to implement those data structures in Python. The goal of this guide is to give you as universal of a graph implementation as possible, but still make it lightweight. That's what allows you to focus on implementing graph algorithms instead of a graph as a data structure. Ideally, you would have a wrapper class representing a graph data structure that you can use to wrap any graph algorithm method you want to implement later.

Note: Simple implementations that we'll create in this guide should cover you in all non-highly-specific use cases. For example, we'll assume that all nodes are labeled by numbers starting from zero. But if you need more comprehensive implementations , we got you covered! You can find complete implementations in the following GitHub repo .

The Graph class will store the graph representation, as well as all other methods you might need to manipulate a graph. Let's take a look at its general structure and dive into implementation afterward:

As you can see, there are several, say, "sections" you should implement in a Graph class. The most important section and the one we'll be focusing on in this section is the Constructor section . That's where you should put your graph implementation (data structure representation). After that, you can implement any graph-related algorithm as a method in this class. Alternatively, you can implement any graph-traversal/graph-search algorithm as a standalone method, and pass in the graph itself. The difference is, quite literally, just in whether the algorithm references self (parent graph) or the passed in graph .

Let's take a look at how to implement each of the mentioned graph representations in the Graph class. In this section, we'll use the previously shown example graph to test each implementation:

How to Implement a List of Edges in Python

As we've stated before, a list of edges doesn't have many real-world applications, but it is often used for illustrative purposes. You can use it when you need a simple implementation of a graph that doesn't unnecessarily complicate the implementation of an algorithm.

Let's take a look at the implementation of the Graph class that uses a list of edges to represent a graph:

As you can see, this implementation is pretty simple. A graph is represented as a list of edges, where each edge is represented by a list in the following fashion: [node1, node2, weight] . Therefore, a graph is effectively a matrix, where each row represents one edge.

Let's create our example graph and see how does the list of edges stores it.

First of all, the example graph has 5 nodes, therefore you create a graph with 5 nodes using the constructor. Then you add all edges to the created graph and print the graph. That will output the following:

As you can see, this output is in line with the example list of edges we've shown in previous sections:

Note: If you wanted to make this graph undirected, you should the constructor in the following way: graph = Graph(5, directed=False) .

How to Implement an Adjacency Matrix in Python

An adjacency matrix is essentially a simple nxn matrix, where n is the number of nodes in a graph. Therefore, we'll implement it as the matrix with num_of_nodes rows and columns. We'll use a list comprehension to construct it and initialize all fields to 0 .

In this case, 0 is a special value referring to the fact that there are no edges in a graph initially. Adding edges is pretty simple, we just need to mark the appropriate field of the matrix with 1 or weight depending on whether a graph is weighted or not:

Now let's test this implementation in the previously described way:

Running the code above will yield the following output:

As expected, the output is the same matrix like the one we've shown in the previous sections:

Note: If you wanted to make this graph undirected, you should the constructor in the following way: graph = Graph(5, directed=False) . In that case, the adjacency matrix will symmetric.

How to Implement an Adjacency List in Python

As we've explained in the previous sections, the best way to represent an adjacency list in Python is by using a dictionary - it has a set of keys and corresponding values .

We'll create one key for each node, and a set of adjacent nodes for each key. That way, we'll effectively create a set of adjacent nodes for each node in a graph. In essence, an adjacent node represents the edge between the key node and the adjacent node, therefore we need to assign a weight to each edge. That's why we'll represent each adjacent node as a tuple - a pair of the name of the adjacent node and the weight of that edge:

Again, let's test the implementation in the previously described way:

The output is identically the same as the linked list described in the previous sections:

types of graph representation

After reading this lesosn, you might ask yourself - What graph representation should I ultimately use? But the answer, as usual, isn't a straightforward one - it depends.

Each graph representation has its pros and cons - it shines in one use-case, but has low performance in others. That's why we've given you a comprehensive overview of graph representations. After reading this guide, you should have an intuitive understanding of graph representations, know how to implement each of them, and when to use each based on a handy list of pros and cons. Therefore, this guide should be a good starting point if you want to dive deeper into implementing graph-related algorithms.

Advide: On the other hand, if you want to dive deeper into the implementation of the graph itself, we advise you to take a look at the following GitHub repo . There you can find more in-depth and comprehensive implementations of graph data structures.

© 2013- 2024 Stack Abuse. All rights reserved.

Close

Data Structures and Algorithms

Chapter 10 graphs.

Show Source |    | About    «   9. 12. Hashing Chapter Summary Exercises   ::   Contents   ::   10. 2. Graph Implementations   »

10. 1. Chapter Introduction: Graphs ¶

10. 1.1. graph terminology and implementation ¶.

Graphs provide the ultimate in data structure flexibility. A graph consists of a set of nodes, and a set of edges where an edge connects two nodes. Trees and lists can be viewed as special cases of graphs.

Graphs are used to model both real-world systems and abstract problems, and are the data structure of choice in many applications. Here is a small sampling of the types of problems that graphs are routinely used for.

Modeling connectivity in computer and communications networks.

Representing an abstract map as a set of locations with distances between locations. This can be used to compute shortest routes between locations such as in a GPS routefinder.

Modeling flow capacities in transportation networks to find which links create the bottlenecks.

Finding a path from a starting condition to a goal condition. This is a common way to model problems in artificial intelligence applications and computerized game players.

Modeling computer algorithms, to show transitions from one program state to another.

Finding an acceptable order for finishing subtasks in a complex activity, such as constructing large buildings.

Modeling relationships such as family trees, business or military organizations, and scientific taxonomies.

The rest of this module covers some basic graph terminology. The following modules will describe fundamental representations for graphs, provide a reference implementation, and cover core graph algorithms including traversal, topological sort, shortest paths algorithms, and algorithms to find the minimal-cost spanning tree. Besides being useful and interesting in their own right, these algorithms illustrate the use of many other data structures presented throughout the course.

A graph \(\mathbf{G} = (\mathbf{V}, \mathbf{E})\) consists of a set of vertices \(\mathbf{V}\) and a set of edges \(\mathbf{E}\) , such that each edge in \(\mathbf{E}\) is a connection between a pair of vertices in \(\mathbf{V}\) . 1 The number of vertices is written \(|\mathbf{V}|\) , and the number of edges is written \(|\mathbf{E}|\) . \(|\mathbf{E}|\) can range from zero to a maximum of \(|\mathbf{V}|^2 - |\mathbf{V}|\) .

Some graph applications require that a given pair of vertices can have multiple or parallel edges connecting them, or that a vertex can have an edge to itself. However, the applications discussed here do not require either of these special cases. To simplify our graph API, we will assume that there are no duplicate edges.

A graph whose edges are not directed is called an undirected graph , as shown in part (a) of the following figure. A graph with edges directed from one vertex to another (as in (b)) is called a directed graph or digraph . A graph with labels associated with its vertices (as in (c)) is called a labeled graph . Associated with each edge may be a cost or weight . A graph whose edges have weights (as in (c)) is said to be a weighted graph .

Figure 10.2.1: Some types of graphs.

An edge connecting Vertices \(a\) and \(b\) is written \((a, b)\) . Such an edge is said to be incident with Vertices \(a\) and \(b\) . The two vertices are said to be adjacent . If the edge is directed from \(a\) to \(b\) , then we say that \(a\) is adjacent to \(b\) , and \(b\) is adjacent from \(a\) . The degree of a vertex is the number of edges it is incident with. For example, Vertex \(e\) below has a degree of three.

In a directed graph, the out degree for a vertex is the number of neighbors adjacent from it (or the number of edges going out from it), while the in degree is the number of neighbors adjacent to it (or the number of edges coming in to it). In (c) above, the in degree of Vertex 1 is two, and its out degree is one.

A sequence of vertices \(v_1, v_2, ..., v_n\) forms a path of length \(n-1\) if there exist edges from \(v_i\) to \(v_{i+1}\) for \(1 \leq i < n\) . A path is a simple path if all vertices on the path are distinct. The length of a path is the number of edges it contains. A cycle is a path of length three or more that connects some vertex \(v_1\) to itself. A cycle is a simple cycle if the path is simple, except for the first and last vertices being the same.

An undirected graph is a connected graph if there is at least one path from any vertex to any other. The maximally connected subgraphs of an undirected graph are called connected components . For example, this figure shows an undirected graph with three connected components.

A graph with relatively few edges is called a sparse graph , while a graph with many edges is called a dense graph . A graph containing all possible edges is said to be a complete graph . A subgraph \(\mathbf{S}\) is formed from graph \(\mathbf{G}\) by selecting a subset \(\mathbf{V}_s\) of \(\mathbf{G}\) ’s vertices and a subset \(\mathbf{E}_s\) of \(\mathbf{G}\) ‘s edges such that for every edge \(e \in \mathbf{E}_s\) , both vertices of \(e\) are in \(\mathbf{V}_s\) . Any subgraph of \(V\) where all vertices in the graph connect to all other vertices in the subgraph is called a clique .n

A graph without cycles is called an acyclic graph . Thus, a directed graph without cycles is called a directed acyclic graph or DAG .

A free tree is a connected, undirected graph with no simple cycles. An equivalent definition is that a free tree is connected and has \(|\mathbf{V}| - 1\) edges.

10. 1.1.1. Graph Representations ¶

There are two commonly used methods for representing graphs. The adjacency matrix for a graph is a \(|\mathbf{V}| \times |\mathbf{V}|\) array. We typically label the vertices from \(v_0\) through \(v_{|\mathbf{V}|-1}\) . Row \(i\) of the adjacency matrix contains entries for Vertex \(v_i\) . Column \(j\) in row \(i\) is marked if there is an edge from \(v_i\) to \(v_j\) and is not marked otherwise. The space requirements for the adjacency matrix are \(\Theta(|\mathbf{V}|^2)\) .

The second common representation for graphs is the adjacency list . The adjacency list is an array of linked lists. The array is \(|\mathbf{V}|\) items long, with position \(i\) storing a pointer to the linked list of edges for Vertex \(v_i\) . This linked list represents the edges by the vertices that are adjacent to Vertex \(v_i\) .

Here is an example of the two representations on a directed graph. The entry for Vertex 0 stores 1 and 4 because there are two edges in the graph leaving Vertex 0, with one going to Vertex 1 and one going to Vertex 4. The list for Vertex 2 stores an entry for Vertex 4 because there is an edge from Vertex 2 to Vertex 4, but no entry for Vertex 3 because this edge comes into Vertex 2 rather than going out.

Figure 10.2.7: Representing a directed graph.

Both the adjacency matrix and the adjacency list can be used to store directed or undirected graphs. Each edge of an undirected graph connecting Vertices \(u\) and \(v\) is represented by two directed edges: one from \(u\) to \(v\) and one from \(v\) to \(u\) . Here is an example of the two representations on an undirected graph. We see that there are twice as many edge entries in both the adjacency matrix and the adjacency list. For example, for the undirected graph, the list for Vertex 2 stores an entry for both Vertex 3 and Vertex 4.

Figure 10.2.8: Representing an undirected graph.

The storage requirements for the adjacency list depend on both the number of edges and the number of vertices in the graph. There must be an array entry for each vertex (even if the vertex is not adjacent to any other vertex and thus has no elements on its linked list), and each edge must appear on one of the lists. Thus, the cost is \(\Theta(|\mathbf{V}| + |\mathbf{E}|)\) .

Sometimes we want to store weights or distances with each each edge, such as in Figure 10.2.1 (c). This is easy with the adjacency matrix, where we will just store values for the weights in the matrix. In Figures 10.2.7 and 10.2.8 we store a value of “1” at each position just to show that the edge exists. That could have been done using a single bit, but since bit manipulation is typically complicated in most programming languages, an implementation might store a byte or an integer at each matrix position. For a weighted graph, we would need to store at each position in the matrix enough space to represent the weight, which might typically be an integer.

The adjacency list needs to explicitly store a weight with each edge. In the adjacency list shown below, each linked list node is shown storing two values. The first is the index for the neighbor at the end of the associated edge. The second is the value for the weight. As with the adjacency matrix, this value requires space to represent, typically an integer.

Which graph representation is more space efficient depends on the number of edges in the graph. The adjacency list stores information only for those edges that actually appear in the graph, while the adjacency matrix requires space for each potential edge, whether it exists or not. However, the adjacency matrix requires no overhead for pointers, which can be a substantial cost, especially if the only information stored for an edge is one bit to indicate its existence. As the graph becomes denser, the adjacency matrix becomes relatively more space efficient. Sparse graphs are likely to have their adjacency list representation be more space efficient.

Example 10.2.1

Assume that a vertex index requires two bytes, a pointer requires four bytes, and an edge weight requires two bytes. Then, each link node in the adjacency list needs \(2 + 2 + 4 = 8\) bytes. The adjacency matrix for the directed graph above requires \(2 |\mathbf{V}^2| = 50\) bytes while the adjacency list requires \(4 |\mathbf{V}| + 8 |\mathbf{E}| = 68\) bytes. For the undirected version of the graph above, the adjacency matrix requires the same space as before, while the adjacency list requires \(4 |\mathbf{V}| + 8 |\mathbf{E}| = 116\) bytes (because there are now 12 edges represented instead of 6).

The adjacency matrix often requires a higher asymptotic cost for an algorithm than would result if the adjacency list were used. The reason is that it is common for a graph algorithm to visit each neighbor of each vertex. Using the adjacency list, only the actual edges connecting a vertex to its neighbors are examined. However, the adjacency matrix must look at each of its \(|\mathbf{V}|\) potential edges, yielding a total cost of \(\Theta(|\mathbf{V}^2|)\) time when the algorithm might otherwise require only \(\Theta(|\mathbf{V}| + |\mathbf{E}|)\) time. This is a considerable disadvantage when the graph is sparse, but not when the graph is closer to full.

10. 1.2. Graph Terminology Questions ¶

Contact Us | | Privacy | | License    «   9. 12. Hashing Chapter Summary Exercises   ::   Contents   ::   10. 2. Graph Implementations   »

Contact Us | | Report a bug

Ensure that you are logged in and have the required permissions to access the test.

A server error has occurred. Please refresh the page or try after some time.

An error has occurred. Please refresh the page or try after some time.

Signup and get free access to 100+ Tutorials and Practice Problems Start Now

Algorithms

  • Linear Search
  • Binary Search
  • Ternary Search
  • Bubble Sort
  • Selection Sort
  • Insertion Sort
  • Counting Sort
  • Bucket Sort
  • Basics of Greedy Algorithms

Graph Representation

  • Breadth First Search
  • Depth First Search
  • Minimum Spanning Tree
  • Shortest Path Algorithms
  • Flood-fill Algorithm
  • Articulation Points and Bridges
  • Biconnected Components
  • Strongly Connected Components
  • Topological Sort
  • Hamiltonian Path
  • Maximum flow
  • Minimum Cost Maximum Flow
  • Basics of String Manipulation
  • String Searching
  • Z Algorithm
  • Manachar’s Algorithm
  • Introduction to Dynamic Programming 1
  • 2 Dimensional
  • State space reduction
  • Dynamic Programming and Bit Masking

Graphs are mathematical structures that represent pairwise relationships between objects. A graph is a flow structure that represents the relationship between various objects. It can be visualized by using the following two basic components:

Nodes: These are the most important components in any graph. Nodes are entities whose relationships are expressed using edges. If a graph comprises 2 nodes $$A$$ and $$B$$ and an undirected edge between them, then it expresses a bi-directional relationship between the nodes and edge.

Edges: Edges are the components that are used to represent the relationships between various nodes in a graph. An edge between two nodes expresses a one-way or two-way relationship between the nodes.

Types of nodes

Root node: The root node is the ancestor of all other nodes in a graph. It does not have any ancestor. Each graph consists of exactly one root node. Generally, you must start traversing a graph from the root node.

Leaf nodes: In a graph, leaf nodes represent the nodes that do not have any successors. These nodes only have ancestor nodes. They can have any number of incoming edges but they will not have any outgoing edges.

Types of graphs

  • Undirected: An undirected graph is a graph in which all the edges are bi-directional i.e. the edges do not point in any specific direction.

enter image description here

  • Directed: A directed graph is a graph in which all the edges are uni-directional i.e. the edges point in a single direction.

enter image description here

Weighted: In a weighted graph, each edge is assigned a weight or cost. Consider a graph of 4 nodes as in the diagram below. As you can see each edge has a weight/cost assigned to it. If you want to go from vertex 1 to vertex 3, you can take one of the following 3 paths:

  • 1 -> 2 -> 3
  • 1 -> 4 -> 3

Therefore the total cost of each path will be as follows: - The total cost of 1 -> 2 -> 3 will be (1 + 2) i.e. 3 units - The total cost of 1 -> 3 will be 1 unit - The total cost of 1 -> 4 -> 3 will be (3 + 2) i.e. 5 units

enter image description here

Cyclic: A graph is cyclic if the graph comprises a path that starts from a vertex and ends at the same vertex. That path is called a cycle. An acyclic graph is a graph that has no cycle.

A tree is an undirected graph in which any two vertices are connected by only one path. A tree is an acyclic graph and has N - 1 edges where N is the number of vertices. Each node in a graph may have one or multiple parent nodes. However, in a tree, each node (except the root node) comprises exactly one parent node.

Note : A root node has no parent.

A tree cannot contain any cycles or self loops, however, the same does not apply to graphs.

enter image description here

Graph representation

You can represent a graph in many ways. The two most common ways of representing a graph is as follows:

Adjacency matrix

An adjacency matrix is a VxV binary matrix A . Element $$A_{i,j}$$ is 1 if there is an edge from vertex i to vertex j else $$A_{i,j}$$ is 0.

Note : A binary matrix is a matrix in which the cells can have only one of two possible values - either a 0 or 1.

The adjacency matrix can also be modified for the weighted graph in which instead of storing 0 or 1 in $$A_{i,j}$$ , the weight or cost of the edge will be stored.

In an undirected graph, if $$A_{i,j}$$ = 1, then $$A_{j,i}$$ = 1. In a directed graph, if $$A_{i,j}$$ = 1, then $$A_{j,i}$$ may or may not be 1.

Adjacency matrix provides constant time access (O(1) ) to determine if there is an edge between two nodes. Space complexity of the adjacency matrix is O($$V^2$$) .

The adjacency matrix of the following graph is: i/j : 1 2 3 4 1 : 0 1 0 1 2 : 1 0 1 0 3 : 0 1 0 1 4 : 1 0 1 0

enter image description here

The adjacency matrix of the following graph is:

i/j : 1 2 3 4 1 : 0 1 0 0 2 : 0 0 0 1 3 : 1 0 0 1 4 : 0 1 0 0

enter image description here

Consider the directed graph given above. Let's create this graph using an adjacency matrix and then show all the edges that exist in the graph.

Input file 4 $$\hspace{2cm}$$ // nodes 5 $$\hspace{2cm}$$//edges 1 2 $$\hspace{1.5cm}$$ //showing edge from node 1 to node 2 2 4 $$\hspace{1.5cm}$$ //showing edge from node 2 to node 4 3 1 $$\hspace{1.5cm}$$ //showing edge from node 3 to node 1 3 4 $$\hspace{1.5cm}$$ //showing edge from node 3 to node 4 4 2 $$\hspace{1.5cm}$$ //showing edge from node 4 to node 2

There is an edge between 3 and 4.

There is no edge between 2 and 3.

Adjacency list

The other way to represent a graph is by using an adjacency list. An adjacency list is an array A of separate lists. Each element of the array A i is a list, which contains all the vertices that are adjacent to vertex i.

For a weighted graph, the weight or cost of the edge is stored along with the vertex in the list using pairs. In an undirected graph, if vertex j is in list $$A_{i}$$ then vertex i will be in list $$A_{j}$$ .

The space complexity of adjacency list is O(V + E) because in an adjacency list information is stored only for those edges that actually exist in the graph. In a lot of cases, where a matrix is sparse using an adjacency matrix may not be very useful. This is because using an adjacency matrix will take up a lot of space where most of the elements will be 0, anyway. In such cases, using an adjacency list is better.

Note: A sparse matrix is a matrix in which most of the elements are zero, whereas a dense matrix is a matrix in which most of the elements are non-zero.

enter image description here

Consider the same undirected graph from an adjacency matrix. The adjacency list of the graph is as follows:

enter image description here

Consider the same directed graph from an adjacency matrix. The adjacency list of the graph is as follows:

A1 → 2 A2 → 4 A3 → 1 → 4 A4 → 2

Consider the directed graph given above. The code for this graph is as follows:

4 $$\hspace{2cm}$$ // nodes 5 $$\hspace{2cm}$$ //edges 1 2 $$\hspace{1.5cm}$$ //showing edge from node 1 to node 2 2 4 $$\hspace{1.5cm}$$ //showing edge from node 2 to node 4 3 1 $$\hspace{1.5cm}$$ //showing edge from node 3 to node 1 3 4 $$\hspace{1.5cm}$$ //showing edge from node 3 to node 4 4 2 $$\hspace{1.5cm}$$ //showing edge from node 4 to node 2

  • Adjacency list of node 1: 2
  • Adjacency list of node 2: 4
  • Adjacency list of node 3: 1 --> 4
  • Adjacency list of node 4: 2

Google

  • An alphabet
  • A special character
  • Minimum 8 characters

A password reset link will be sent to the following email id

Javatpoint Logo

  • Data Structure
  • Design Pattern

DS Tutorial

Ds linked list, ds searching, differences.

JavaTpoint

  • Send your Feedback to [email protected]

Help Others, Please Share

facebook

Learn Latest Tutorials

Splunk tutorial

Transact-SQL

Tumblr tutorial

Reinforcement Learning

R Programming tutorial

R Programming

RxJS tutorial

React Native

Python Design Patterns

Python Design Patterns

Python Pillow tutorial

Python Pillow

Python Turtle tutorial

Python Turtle

Keras tutorial

Preparation

Aptitude

Verbal Ability

Interview Questions

Interview Questions

Company Interview Questions

Company Questions

Trending Technologies

Artificial Intelligence

Artificial Intelligence

AWS Tutorial

Cloud Computing

Hadoop tutorial

Data Science

Angular 7 Tutorial

Machine Learning

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures

DAA tutorial

Operating System

Computer Network tutorial

Computer Network

Compiler Design tutorial

Compiler Design

Computer Organization and Architecture

Computer Organization

Discrete Mathematics Tutorial

Discrete Mathematics

Ethical Hacking

Ethical Hacking

Computer Graphics Tutorial

Computer Graphics

Software Engineering

Software Engineering

html tutorial

Web Technology

Cyber Security tutorial

Cyber Security

Automata Tutorial

C Programming

C++ tutorial

Control System

Data Mining Tutorial

Data Mining

Data Warehouse Tutorial

Data Warehouse

RSS Feed

Library homepage

  • school Campus Bookshelves
  • menu_book Bookshelves
  • perm_media Learning Objects
  • login Login
  • how_to_reg Request Instructor Account
  • hub Instructor Commons

Margin Size

  • Download Page (PDF)
  • Download Full Book (PDF)
  • Periodic Table
  • Physics Constants
  • Scientific Calculator
  • Reference & Cite
  • Tools expand_more
  • Readability

selected template will load here

This action is not available.

Engineering LibreTexts

8.4: Graph Representations

  • Last updated
  • Save as PDF
  • Page ID 49318

  • Wikibooks - Data Structures

\( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

\( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)

\( \newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\)

( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\)

\( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)

\( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\)

\( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)

\( \newcommand{\Span}{\mathrm{span}}\)

\( \newcommand{\id}{\mathrm{id}}\)

\( \newcommand{\kernel}{\mathrm{null}\,}\)

\( \newcommand{\range}{\mathrm{range}\,}\)

\( \newcommand{\RealPart}{\mathrm{Re}}\)

\( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)

\( \newcommand{\Argument}{\mathrm{Arg}}\)

\( \newcommand{\norm}[1]{\| #1 \|}\)

\( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\AA}{\unicode[.8,0]{x212B}}\)

\( \newcommand{\vectorA}[1]{\vec{#1}}      % arrow\)

\( \newcommand{\vectorAt}[1]{\vec{\text{#1}}}      % arrow\)

\( \newcommand{\vectorB}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

\( \newcommand{\vectorC}[1]{\textbf{#1}} \)

\( \newcommand{\vectorD}[1]{\overrightarrow{#1}} \)

\( \newcommand{\vectorDt}[1]{\overrightarrow{\text{#1}}} \)

\( \newcommand{\vectE}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash{\mathbf {#1}}}} \)

Adjacency Matrix Representation

An adjacency matrix is one of the two common ways to represent a graph. The adjacency matrix shows which nodes are adjacent to one another. Two nodes are adjacent if there is an edge connecting them. In the case of a directed graph, if node \(j\) is adjacent to node \(i\), there is an edge from \(i\) to \(j\). In other words, if \(j\) is adjacent to \(i\), you can get from \(i\) to \(j\) by traversing one edge. For a given graph with \(n\) nodes, the adjacency matrix will have dimensions of \(n\times n\). For an unweighted graph, the adjacency matrix will be populated with boolean values.

For any given node \(i\), you can determine its adjacent nodes by looking at row \(\left(i,\left[1..n\right]\right)\) of the adjacency matrix. A value of true at \(\left(i,j\right)\) indicates that there is an edge from node \(i\) to node \(j\), and false indicating no edge. In an undirected graph, the values of \(\left(i,j\right)\) and \(\left(j,i\right)\) will be equal. In a weighted graph, the boolean values will be replaced by the weight of the edge connecting the two nodes, with a special value that indicates the absence of an edge.

The memory use of an adjacency matrix is \(O(n^{2})\).

Adjacency List Representation

The adjacency list is another common representation of a graph. There are many ways to implement this adjacency representation. One way is to have the graph maintain a list of lists, in which the first list is a list of indices corresponding to each node in the graph. Each of these refer to another list that stores the index of each adjacent node to this one. It might also be useful to associate the weight of each link with the adjacent node in this list.

Example: An undirected graph contains four nodes 1, 2, 3 and 4. 1 is linked to 2 and 3. 2 is linked to 3. 3 is linked to 4.

3 - [1, 2, 4]

It might be useful to store the list of all the nodes in the graph in a hash table. The keys then would correspond to the indices of each node and the value would be a reference to the list of adjacent node indices.

Another implementation might require that each node keep a list of its adjacent nodes.

  • Math Article

Graphical Representation

Class Registration Banner

Graphical Representation is a way of analysing numerical data. It exhibits the relation between data, ideas, information and concepts in a diagram. It is easy to understand and it is one of the most important learning strategies. It always depends on the type of information in a particular domain. There are different types of graphical representation. Some of them are as follows:

  • Line Graphs – Line graph or the linear graph is used to display the continuous data and it is useful for predicting future events over time.
  • Bar Graphs – Bar Graph is used to display the category of data and it compares the data using solid bars to represent the quantities.
  • Histograms – The graph that uses bars to represent the frequency of numerical data that are organised into intervals. Since all the intervals are equal and continuous, all the bars have the same width.
  • Line Plot – It shows the frequency of data on a given number line. ‘ x ‘ is placed above a number line each time when that data occurs again.
  • Frequency Table – The table shows the number of pieces of data that falls within the given interval.
  • Circle Graph – Also known as the pie chart that shows the relationships of the parts of the whole. The circle is considered with 100% and the categories occupied is represented with that specific percentage like 15%, 56%, etc.
  • Stem and Leaf Plot – In the stem and leaf plot, the data are organised from least value to the greatest value. The digits of the least place values from the leaves and the next place value digit forms the stems.
  • Box and Whisker Plot – The plot diagram summarises the data by dividing into four parts. Box and whisker show the range (spread) and the middle ( median) of the data.

Graphical Representation

General Rules for Graphical Representation of Data

There are certain rules to effectively present the information in the graphical representation. They are:

  • Suitable Title: Make sure that the appropriate title is given to the graph which indicates the subject of the presentation.
  • Measurement Unit: Mention the measurement unit in the graph.
  • Proper Scale: To represent the data in an accurate manner, choose a proper scale.
  • Index: Index the appropriate colours, shades, lines, design in the graphs for better understanding.
  • Data Sources: Include the source of information wherever it is necessary at the bottom of the graph.
  • Keep it Simple: Construct a graph in an easy way that everyone can understand.
  • Neat: Choose the correct size, fonts, colours etc in such a way that the graph should be a visual aid for the presentation of information.

Graphical Representation in Maths

In Mathematics, a graph is defined as a chart with statistical data, which are represented in the form of curves or lines drawn across the coordinate point plotted on its surface. It helps to study the relationship between two variables where it helps to measure the change in the variable amount with respect to another variable within a given interval of time. It helps to study the series distribution and frequency distribution for a given problem.  There are two types of graphs to visually depict the information. They are:

  • Time Series Graphs – Example: Line Graph
  • Frequency Distribution Graphs – Example: Frequency Polygon Graph

Principles of Graphical Representation

Algebraic principles are applied to all types of graphical representation of data. In graphs, it is represented using two lines called coordinate axes. The horizontal axis is denoted as the x-axis and the vertical axis is denoted as the y-axis. The point at which two lines intersect is called an origin ‘O’. Consider x-axis, the distance from the origin to the right side will take a positive value and the distance from the origin to the left side will take a negative value. Similarly, for the y-axis, the points above the origin will take a positive value, and the points below the origin will a negative value.

Principles of graphical representation

Generally, the frequency distribution is represented in four methods, namely

  • Smoothed frequency graph
  • Pie diagram
  • Cumulative or ogive frequency graph
  • Frequency Polygon

Merits of Using Graphs

Some of the merits of using graphs are as follows:

  • The graph is easily understood by everyone without any prior knowledge.
  • It saves time
  • It allows us to relate and compare the data for different time periods
  • It is used in statistics to determine the mean, median and mode for different data, as well as in the interpolation and the extrapolation of data.

Example for Frequency polygonGraph

Here are the steps to follow to find the frequency distribution of a frequency polygon and it is represented in a graphical way.

  • Obtain the frequency distribution and find the midpoints of each class interval.
  • Represent the midpoints along x-axis and frequencies along the y-axis.
  • Plot the points corresponding to the frequency at each midpoint.
  • Join these points, using lines in order.
  • To complete the polygon, join the point at each end immediately to the lower or higher class marks on the x-axis.

Draw the frequency polygon for the following data

Mark the class interval along x-axis and frequencies along the y-axis.

Let assume that class interval 0-10 with frequency zero and 90-100 with frequency zero.

Now calculate the midpoint of the class interval.

Using the midpoint and the frequency value from the above table, plot the points A (5, 0), B (15, 4), C (25, 6), D (35, 8), E (45, 10), F (55, 12), G (65, 14), H (75, 7), I (85, 5) and J (95, 0).

To obtain the frequency polygon ABCDEFGHIJ, draw the line segments AB, BC, CD, DE, EF, FG, GH, HI, IJ, and connect all the points.

types of graph representation

Frequently Asked Questions

What are the different types of graphical representation.

Some of the various types of graphical representation include:

  • Line Graphs
  • Frequency Table
  • Circle Graph, etc.

Read More:  Types of Graphs

What are the Advantages of Graphical Method?

Some of the advantages of graphical representation are:

  • It makes data more easily understandable.
  • It saves time.
  • It makes the comparison of data more efficient.

Leave a Comment Cancel reply

Your Mobile number and Email id will not be published. Required fields are marked *

Request OTP on Voice Call

Post My Comment

types of graph representation

Very useful for understand the basic concepts in simple and easy way. Its very useful to all students whether they are school students or college sudents

Thanks very much for the information

types of graph representation

Register with BYJU'S & Download Free PDFs

Register with byju's & watch live videos.

Tutorial Playlist

Data structure tutorial, arrays in data structures: a guide with examples, all you need to know about two-dimensional arrays, all you need to know about a linked list in a data structure, the complete guide to implement a singly linked list, the ultimate guide to implement a doubly linked list, the fundamentals for understanding circular linked list, the ultimate guide to understand the differences between stack and queue.

Implementing Stacks in Data Structures

Your One-Stop Solution for Stack Implementation Using Array

Your one-stop solution for queue implementation using array, your one-stop solution to learn depth-first search(dfs) algorithm from scratch, your one-stop solution for stack implementation using linked-list, the definitive guide to understand stack vs heap memory allocation, all you need to know about linear search algorithm, all you need to know about breadth-first search algorithm, a one-stop solution for using binary search trees in data structure.

The Best Tutorial to Understand Trees in Data Structure

A Complete Guide to Implement Binary Tree in Data Structure

A holistic look at using avl trees in data structures, all you need to know about tree traversal in data structure, the best and easiest way to understand an algorithm, the best guide you’ll ever need to understand b-tree in data structure, the best guide you'll ever need to understand spanning tree in data structure, a one-stop solution guide to understand data structure and algorithm complexity, your one-stop solution to understand shell sort algorithm, your one-stop solution to quick sort algorithm, the most useful guide to learn selection sort algorithm, everything you need to know about radix sort algorithm, everything you need to know about the counting sort algorithm, everything you need to know about the merge sort algorithm, insertion sort algorithm: one-stop solution that will help you understand insertion sort, everything you need to know about the bubble sort algorithm, the best guide you’ll ever need to understand bucket sort algorithm, your one-stop solution to understand recursive algorithm in programming, the definitive guide to understanding greedy algorithm, your one-stop solution to understand backtracking algorithm, the fundamentals of the bellman-ford algorithm, your one-stop solution for graphs in data structures, the best guide to understand and implement solutions for tower of hanoi puzzle, a simplified and complete guide to learn space and time complexity, all you need to know about the knapsack problem : your complete guide, the fibonacci series: mathematical and programming interpretation, the holistic look at longest common subsequence problem, the best article to understand what is dynamic programming, a guide to implement longest increasing subsequence using dynamic programming, a holistic guide to learn stop solution using dynamic programming, one stop solution to all the dynamic programming problems, understanding the fundamentals of binomial distribution, here’s all you need to know about minimum spanning tree in data structures, understanding the difference between array and linked list, the best article out there to understand the b+ tree in data structure.

A Comprehensive Look at Queue in Data Structure

Your One-Stop Solution to Understand Coin Change Problem

The best way to understand the matrix chain multiplication problem, your one-stop solution to learn floyd-warshall algorithm for using dynamic programming, the best tutorial you'll ever need for queue implementation using linked list, how to create a fake news detection system, all you need to know about how to create a react js portfolio project, a complete guide on the role of ai in healthcare, the best guide to learn how to make a wireframe: what is a wireframe, the best dsa projects for your resume, the best guide to understanding the working and implementation of selective repeat arq, one stop guide to understanding network layer in the osi model, the working and implementation of data-link layer in the osi model, top 5 best coding books you must read, the working and implementation of physical layer in the osi model, how to create an instagram clone using react, reactjs vs vuejs, what is graph in data structure & types of graph.

Lesson 38 of 68 By Ravikiran A S

Your One-Stop Solution for Graphs in Data Structures

Table of Contents

Graphs in data structures are non-linear data structures made up of a finite number of nodes or vertices and the edges that connect them. Graphs in data structures are used to address real-world problems in which it represents the problem area as a network like telephone networks, circuit networks, and social networks. For example, it can represent a single user as nodes or vertices in a telephone network, while the link between them via telephone represents edges.

Want a Top Software Development Job? Start Here!

Want a Top Software Development Job? Start Here!

What Are Graphs in Data Structure?

A graph is a non-linear kind of data structure made up of nodes or vertices and edges. The edges connect any two nodes in the graph, and the nodes are also known as vertices.

what-is-graphs-in-data-structure

This graph has a set of vertices V= { 1,2,3,4,5} and a set of edges E= { (1,2),(1,3),(2,3),(2,4),(2,5),(3,5),(4,50 }.

Now that you’ve learned about the definition of graphs in data structures, you will learn about their various types.

Types of Graphs in Data Structures

There are different types of graphs in data structures, each of which is detailed below.

1. Finite Graph

The graph G=(V, E) is called a finite graph if the number of vertices and edges in the graph is limited in number

FINITE-GRAPH-IN-GRAPHS-IN-DATA-STRUCTURE

2. Infinite Graph

The graph G=(V, E) is called a finite graph if the number of vertices and edges in the graph is interminable.

infinite-graph-data-structure.

3. Trivial Graph

A graph G= (V, E) is trivial if it contains only a single vertex and no edges.

trivial-graph-data-structure

4. Simple Graph

If each pair of nodes or vertices in a graph G=(V, E) has only one edge, it is a simple graph. As a result, there is just one edge linking two vertices, depicting one-to-one interactions between two elements.

simple-graph-data-structure

5. Multi Graph

If there are numerous edges between a pair of vertices in a graph G= (V, E), the graph is referred to as a multigraph. There are no self-loops in a Multigraph.

multi-graph-in-data-structure

6. Null Graph

It's a reworked version of a trivial graph. If several vertices but no edges connect them, a graph G= (V, E) is a null graph. 

null-graph-data-structure.

7. Complete Graph

If a graph G= (V, E) is also a simple graph, it is complete. Using the edges, with n number of vertices must be connected. It's also known as a full graph because each vertex's degree must be n-1.

complete-graph-in-data-structure.

8. Pseudo Graph

If a graph G= (V, E) contains a self-loop besides other edges, it is a pseudograph.

pseudo-graph-in-data-structure.

9. Regular Graph

If a graph G= (V, E) is a simple graph with the same degree at each vertex, it is a regular graph. As a result, every whole graph is a regular graph.

regular-graph-in-data-structure.

10. Weighted Graph

A graph G= (V, E) is called a labeled or weighted graph because each edge has a value or weight representing the cost of traversing that edge.

weighted-graph-in-data-structure

11. Directed Graph

A directed graph also referred to as a digraph, is a set of nodes connected by edges, each with a direction.

directed-graph-in-data-structure

12. Undirected Graph

An undirected graph comprises a set of nodes and links connecting them. The order of the two connected vertices is irrelevant and has no direction. You can form an undirected graph with a finite number of vertices and edges.

undirected-graph-in-data-structure.

13. Connected Graph

If there is a path between one vertex of a graph data structure and any other vertex, the graph is connected.

connected-graph-in-data-structure.

14. Disconnected Graph

When there is no edge linking the vertices, you refer to the null graph as a disconnected graph.

diconnected-graph-in-data-structure.

15. Cyclic Graph

If a graph contains at least one graph cycle, it is considered to be cyclic.

cyclic-graph-in-data-structure

16. Acyclic Graph

When there are no cycles in a graph, it is called an acyclic graph.

acyclic-graph-in-data-structure

17. Directed Acyclic Graph

It's also known as a directed acyclic graph (DAG), and it's a graph with directed edges but no cycle. It represents the edges using an ordered pair of vertices since it directs the vertices and stores some data.

directed-acyclic-graph-in-data-structure

18. Subgraph

The vertices and edges of a graph that are subsets of another graph are known as a subgraph.

subgraph-in-data-structure

After you learn about the many types of graphs in graphs in data structures, you will move on to graph terminologies.

Terminologies of Graphs in Data Structures

Following are the basic terminologies of graphs in data structures:

  • An edge is one of the two primary units used to form graphs. Each edge has two ends, which are vertices to which it is attached.
  • If two vertices are endpoints of the same edge, they are adjacent.
  • A vertex's outgoing edges are directed edges that point to the origin.
  • A vertex's incoming edges are directed edges that point to the vertex's destination.
  • The total number of edges occurring to a vertex in a graph is its degree.
  • The out-degree of a vertex in a directed graph is the total number of outgoing edges, whereas the in-degree is the total number of incoming edges.
  • A vertex with an in-degree of zero is referred to as a source vertex, while one with an out-degree of zero is known as sink vertex.
  • An isolated vertex is a zero-degree vertex that is not an edge's endpoint.
  • A path is a set of alternating vertices and edges, with each vertex connected by an edge.
  • The path that starts and finishes at the same vertex is known as a cycle.
  • A path with unique vertices is called a simple path.
  • For each pair of vertices x, y, a graph is strongly connected if it contains a directed path from x to y and a directed path from y to x.
  •  A directed graph is weakly connected if all of its directed edges are replaced with undirected edges, resulting in a connected graph. A weakly linked graph's vertices have at least one out-degree or in-degree.
  • A tree is a connected forest. The primary form of the tree is called a rooted tree, which is a free tree.
  • A spanning subgraph that is also a tree is known as a spanning tree.
  • A connected component is the unconnected graph's most connected subgraph.
  • A bridge, which is an edge of removal, would sever the graph.
  • Forest is a graph without a cycle.

Following that, you will look at the graph representation in this data structures tutorial.

Representation of Graphs in Data Structures

Graphs in data structures are used to represent the relationships between objects. Every graph consists of a set of points known as vertices or nodes connected by lines known as edges. The vertices in a network represent entities.

The most frequent graph representations are the two that follow:

  • Adjacency matrix
  • Adjacency list

You’ll look at these two representations of graphs in data structures in more detail:

Adjacency Matrix

  • A sequential representation is an adjacency matrix.
  • It's used to show which nodes are next to one another. I.e., is there any connection between nodes in a graph?
  • You create an MXM matrix G for this representation. If an edge exists between vertex a and vertex b, the corresponding element of G, gi,j = 1, otherwise gi,j = 0.
  • If there is a weighted graph, you can record the edge's weight instead of 1s and 0s.

Undirected Graph Representation

graph-representation-in-data-structure-NEW.

Directed Graph Representation

directed-graph-representation-in-data-structure.

Weighted Undirected Graph Representation 

Weight or cost is indicated at the graph's edge, a weighted graph representing these values in the matrix.

unweighted-graph-representation-in-data-structure.

Adjacency List

  • A linked representation is an adjacency list.
  • You keep a list of neighbors for each vertex in the graph in this representation. It means that each vertex in the graph has a list of its neighboring vertices.
  • You have an arra of vertices indexed by the vertex number, and the corresponding array member for each vertex x points to a singly linked list of x's neighbors.

Weighted Undirected Graph Representation Using Linked-List

linked-list-adjancency-list-graph-represenatation-in-data-structure.

Weighted Undirected Graph Representation Using an Array

arrayy-adjancency-list-graph-represenatation-in-data-structure

You will now see which all operations are conducted in graphs data structure after understanding the representation of graphs in the data structure.

Also Read: Linked List in A Data Structure

Operations on Graphs in Data Structures

The operations you perform on the graphs in data structures are listed below:

  • Creating graphs
  • Insert vertex
  • Delete vertex
  • Insert edge 
  • Delete edge

You will go over each operation in detail one by one:

Creating Graphs

There are two techniques to make a graph:

1. Adjacency Matrix

The adjacency matrix of a simple labeled graph, also known as the connection matrix, is a matrix with rows and columns labeled by graph vertices and a 1 or 0 in position depending on whether they are adjacent or not.

2. Adjacency List

A finite graph is represented by an adjacency list, which is a collection of unordered lists. Each unordered list describes the set of neighbors of a particular vertex in the graph within an adjacency list.

Insert Vertex

When you add a vertex that after introducing one or more vertices or nodes, the graph's size grows by one, increasing the matrix's size by one at the row and column levels.

add-vertex-operation-on-graph-in-data-structure

Delete Vertex

  • Deleting a vertex refers to removing a specific node or vertex from a graph that has been saved.
  • If a removed node appears in the graph, the matrix returns that node. If a deleted node does not appear in the graph, the matrix returns the node not available.

delete-vertex-operation-on-graph-in-data-structure

Insert Edge

Connecting two provided vertices can be used to add an edge to a graph.

add-edge-operation-on-graph-in-data-structure

Delete Edge

The connection between the vertices or nodes can be removed to delete an edge.

delete-edge-operation-on-graph-in-data-structure

The types of graph traversal algorithms will be discussed next in the graphs in this data structures tutorial.

Graph Traversal Algorithm 

The process of visiting or updating each vertex in a graph is known as graph traversal. The sequence in which they visit the vertices is used to classify such traversals. Graph traversal is a subset of tree traversal.

There are two techniques to implement a graph traversal algorithm:

  • Breadth-first search
  • Depth-first search

Breadth-First Search or BFS

BFS is a search technique for finding a node in a graph data structure that meets a set of criteria. 

  • It begins at the root of the graph and investigates all nodes at the current depth level before moving on to nodes at the next depth level.
  • To maintain track of the child nodes that have been encountered but not yet inspected, more memory, generally you require a queue.

Algorithm of breadth-first search

Step 1: Consider the graph you want to navigate.

Step 2: Select any vertex in your graph, say v1, from which you want to traverse the graph.

Step 3: Examine any two data structures for traversing the graph.

  • Visited array (size of the graph)
  • Queue data structure

Step 4: Starting from the vertex, you will add to the visited array, and afterward, you will v1's adjacent vertices to the queue data structure.

Step 5: Now, using the FIFO concept, you must remove the element from the queue, put it into the visited array, and then return to the queue to add the adjacent vertices of the removed element.

Step 6: Repeat step 5 until the queue is not empty and no vertex is left to be visited.

breadth-first-search-in-graph-data-structure

Depth-First Search or DFS

DFS is a search technique for finding a node in a graph data structure that meets a set of criteria. 

  • The depth-first search (DFS) algorithm traverses or explores data structures such as trees and graphs. The DFS algorithm begins at the root node and examines each branch as far as feasible before backtracking.
  • To maintain track of the child nodes that have been encountered but not yet inspected, more memory, generally a stack , is required.

Algorithm of depth-first search

Step 2: Select any vertex in our graph, say v1, from which you want to begin traversing the graph.

  • Stack data structure

Step 4: Insert v1 into the array's first block and push all the adjacent nodes or vertices of vertex v1 into the stack.

Step 5: Now, using the FIFO principle, pop the topmost element and put it into the visited array, pushing all of the popped element's nearby nodes into it.

Step 6: If the topmost element of the stack is already present in the array, discard it instead of inserting it into the visited array.

Step 7: Repeat step 6 until the stack data structure isn't empty.                       

depth-first-search-in-graph-data-structure

You will now look at applications of graph data structures after understanding the graph traversal algorithm in this tutorial.

Application of Graphs in Data Structures

Following  are some applications of graphs in data structures:

  • Graphs are used in computer science to depict the flow of computation.
  • Users on Facebook are referred to as vertices, and if they are friends, there is an edge connecting them. The Friend Suggestion system on Facebook is based on graph theory.
  • You come across the Resource Allocation Graph in the Operating System, where each process and resource are regarded vertically. Edges are drawn from resources to assigned functions or from the requesting process to the desired resource. A stalemate will develop if this results in the establishment of a cycle.
  • Web pages are referred to as vertices on the World Wide Web. Suppose there is a link from page A to page B that can represent an edge. This application is an illustration of a directed graph.
  • Graph transformation systems manipulate graphs in memory using rules. Graph databases store and query graph-structured data in a transaction-safe, permanent manner.

Finally, in this tutorial, you’ll look at the code for the graphs in data structures       

Code Implementation of Graphs in Data Structures

You learned what a graph data structure is and the many types of graph data structures in this “graphs in data structures” tutorial. Following that, you learned about the graph traversal method, which includes the breadth-first and depth-first search algorithms, as well as several graph data structure applications.

"Breadth-first search or BFS "will be your next topic, where you will learn about the breadth-first search algorithm and how to traverse tree and graph data structure using BFS. If you want to learn more about data structures and programming languages , check out simplilearn's Post Graduate Program in Full Stack Web Development Automation Testing Masters might just be what you need. The bootcamp is offered in collaboration with Caltech CTME and will provide you with the work-ready software development skills , industry credentials and global recognition you need to succeed now.

If you have any doubts regarding the "graphs in data structures "article, please feel free to ask in the comment section below. We will be happy to resolve your problems as soon as possible. Until then, stay tuned with Simplilearn’s channel and keep learning.

1. Where are graph data structures used in real life?

You most likely utilise social networking platforms such as Facebook, LinkedIn, Instagram, and others. A wonderful example of a graph in usage is social media. Graphs are used in social media to hold information about each user. Every user is a node in this case, just like in Graph. Similarly, Google Maps is another application that makes use of graphs. In the case of Google Maps, each place is referred to as a node, and the roads that connect them are referred to as edges.

2. What are the different types of graphs in data structure?

A graph is a non-linear data structure composed of nodes and edges. They come in a variety of forms. Namely, they are Finite Graphs, Infinite Graphs, Trivial Graphs, Simple Graphs, Multi Graphs, Null Graphs, Complete Graphs, Pseudo Graphs, Regular Graphs, Labeled Graphs, Digraph Graphs, Subgraphs, Connected or Disconnected Graphs, and Cyclic Graphs.

3. How many types of graphs are there in data structure?

They are of 14 to 15 types. However, the most commonly used graph is the finite graph.

4. What is a complete graph in data structure?

A graph is considered to be complete if there is an edge between every pair of vertices in the graph. In other words, all of the graph's vertices are connected to the remainder of the graph's vertices. A full graph of 'n' vertices has precisely nC2 edges and is written as Kn.

5. What is a directed acyclic graph?

A directed acyclic graph (DAG) is a graph that is directed and has no cycles linking the other edges in computer science and mathematics. This indicates that traversing the complete graph from one edge is impossible. The edges of the directed graph can only move in one direction. The graph is a topological sorting in which each node has a specific order.

6. What is graph in data structure?

A graph is a type of non-linear data structure made up of vertices and edges. Vertices are also known as nodes, while edges are lines or arcs that link any two nodes in the network. In more technical terms, a graph comprises vertices (V) and edges (E). The graph is represented as G(E, V).

7. What is graph in data structure and its application?

A graph is a non-linear data structure made up of vertices (or nodes) linked by edges (or arcs), which can be directed or undirected. Graphs are used in computer science to depict the flow of computation.

8. How are graphs useful when interpreting data?

Graphs are a popular way to visually depict data connections. A graph's objective is to convey too many or intricate facts to be fully expressed in words and in less space. However, do not use graphs for little quantities of data that may be expressed in a phrase.

Find our Full Stack Java Developer Online Bootcamp in top cities:

About the author.

Ravikiran A S

Ravikiran A S works with Simplilearn as a Research Analyst. He an enthusiastic geek always in the hunt to learn the latest technologies. He is proficient with Java Programming Language, Big Data, and powerful Big Data Frameworks like Apache Hadoop and Apache Spark.

Recommended Programs

Full Stack Java Developer

Full Stack Web Developer - MEAN Stack

Automation Testing Masters Program

*Lifetime access to high-quality, self-paced e-learning content.

Recommended Resources

Implementing Stacks in Data Structures

Big Data Career Guide: A Comprehensive Playbook to Becoming a Big Data Engineer

What is Data Structure : Types, Classifications, and Applications

What is Data Structure : Types, Classifications, and Applications

The Best Tutorial to Understand Trees in Data Structure

Data Science Career Guide: A Comprehensive Playbook To Becoming A Data Scientist

  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.

Types of Graphs and Charts And Their Uses

If you are wondering what are the different types of graphs and charts ,   their uses and names, this page summarizes them with examples and pictures.

Although it is hard to tell what are all the types of graphs, this page consists all of the common types of statistical graphs and charts (and their meanings) widely used in any science.

1. Line Graphs

A line chart graphically displays data that changes continuously over time. Each line graph consists of points that connect data to show a trend (continuous change). Line graphs have an x-axis and a y-axis. In the most cases, time is distributed on the horizontal axis.

Uses of line graphs:

  • When you want  to show trends . For example, how house prices have increased over time.
  • When you want  to make predictions based on a data history over time.
  • When comparing  two or more different variables, situations, and information over a given period of time.

The following line graph shows annual sales of a particular business company for the period of six consecutive years:

Note: the above example is with 1 line. However, one line chart can compare multiple trends by several distributing lines.

2. Bar Charts

Bar charts represent categorical data with rectangular bars (to understand what is categorical data see categorical data examples ). Bar graphs are among the most popular types of graphs and charts in economics, statistics, marketing, and visualization in digital customer experience . They are commonly used to compare several categories of data.

Each rectangular bar has length and height proportional to the values that they represent.

One axis of the bar chart presents the categories being compared. The other axis shows a measured value.

Bar Charts Uses:

  • When you want to display data that are grouped into nominal or ordinal categories (see nominal vs ordinal data ).
  • To compare data among different categories.
  • Bar charts can also show large   data changes over time.
  • Bar charts are ideal for visualizing the distribution of data when we have more than three categories.

The bar chart below represents the total sum of sales for Product A and Product B over three years.

The bars are 2 types: vertical or horizontal. It doesn’t matter which kind you will use. The above one is a vertical type.

3. Pie Charts

When it comes to statistical types of graphs and charts, the pie chart (or the circle chart) has a crucial place and meaning. It displays data and statistics in an easy-to-understand ‘pie-slice’ format and illustrates numerical proportion.

Each pie slice is relative to the size of a particular category in a given group as a whole. To say it in another way, the pie chart brakes down a group into smaller pieces. It shows part-whole relationships.

To make a pie chart, you need a list of categorical variables and numerical variables.

Pie Chart Uses:

  • When you want to create and represent the composition of something.
  • It is very useful for displaying nominal or ordinal categories of data.
  • To show percentage or proportional data.
  • When comparing areas of growth within a business such as profit.
  • Pie charts work best for displaying data for 3 to 7 categories.

The pie chart below represents the proportion of types of transportation used by 1000 students to go to their school.

Pie charts are widely used by data-driven marketers for displaying marketing data.

4. Histogram

A histogram shows continuous data in ordered rectangular columns (to understand what is continuous data see our post discrete vs continuous data ). Usually, there are no gaps between the columns.

The histogram displays a frequency distribution (shape) of a data set. At first glance, histograms look alike to bar graphs. However, there is a key difference between them. Bar Chart represents categorical data and histogram represent continuous data.

Histogram Uses:

  • When the data is continuous .
  • When you want to represent the shape of the data’s distribution .
  • When you want to see whether the outputs of two or more processes are different.
  • To summarize large data sets graphically.
  • To communicate the data distribution quickly to others.

The histogram below represents per capita income for five age groups.

Histograms are very widely used in statistics, business, and economics.

5. Scatter plot

The scatter plot is an X-Y diagram that shows a relationship between two variables. It is used to plot data points on a vertical and a horizontal axis. The purpose is to show how much one variable affects another.

Usually, when there is a relationship between 2 variables, the first one is called independent. The second variable is called dependent because its values depend on the first variable.

Scatter plots also help you predict the behavior of one variable (dependent) based on the measure of the other variable (independent).

Scatter plot uses:

  • When trying to find out whether there is a relationship between 2 variables .
  • To predict  the behavior of dependent variable based on the measure of the independent variable.
  • When having paired numerical data.
  • When working with  root cause analysis tools  to identify the potential for problems.
  • When you just want to visualize the correlation between 2 large datasets without regard to time .

The below Scatter plot presents data for 7 online stores, their monthly e-commerce sales, and online advertising costs for the last year.

The orange line you see in the plot is called “line of best fit” or a “trend line”. This line is used to help us make predictions that are based on past data.

The Scatter plots are used widely in data science and statistics. They are a great tool for visualizing linear regression models .

More examples and explanation for scatter plots you can see in our post what does a scatter plot show and simple linear regression examples .

6. Venn Chart

Venn Diagram (also called primary diagram, set diagram or logic diagrams) uses overlapping circles to visualize the logical relationships between two or more group of items.

Venn Diagram is one of the types of graphs and charts used in scientific and engineering presentations, in computer applications, in maths, and in statistics.

The basic structure of the Venn diagram is usually overlapping circles. The items in the overlapping section have specific common characteristics. Items in the outer portions of the circles do not have common traits.

Venn Chart Uses:

  • When you want to compare and contrast groups of things.
  • To categorize or group items.
  • To illustrate logical relationships from various datasets.
  • To identify all the possible relationships between collections of datasets.

The following science example of Venn diagram compares the features of birds and bats.

7. Area Charts 

Area Chart Uses:

  • When you want to show trends , rather than express specific values.
  • To show a simple comparison of the trend of data sets over the period of time.
  • To display the magnitude of a change.
  • To compare a small number of categories.

The area chart has 2 variants: a variant with data plots overlapping each other and a variant with data plots stacked on top of each other (known as stacked area chart – as the shown in the following example).

The area chart below shows quarterly sales for product categories A and B for the last year.

This area chart shows you a quick comparison of the trend in the quarterly sales of Product A and Product B over the period of the last year.

8. Spline Chart

The Spline Chart is one of the most widespread types of graphs and charts used in statistics. It is a form of the line chart that represent smooth curves through the different data points.

Spline charts possess all the characteristics of a line chart except that spline charts have a fitted curved line to join the data points. In comparison, line charts connect data points with straight lines.

Spline Chart   Uses:

  • When you want to plot data that requires the usage of curve-fitting such as a product lifecycle chart or an impulse-response chart.
  • Spline charts are often used in designing Pareto charts .
  • Spline chart also is often used for data modeling by when you have limited number of data points and estimating the intervening values.

The following spline chart example shows sales of a company through several months of a year:

9. Box and Whisker Chart

A box and whisker chart is a statistical graph for displaying sets of numerical data through their quartiles. It displays a frequency distribution of the data.

The box and whisker chart helps you to display the spread and skewness for a given set of data using the five number summary principle: minimum, maximum, median, lower and upper quartiles. The ‘five-number summary’ principle allows providing a statistical summary for a particular set of numbers. It shows you the range (minimum and maximum numbers), the spread (upper and lower quartiles), and the center (median) for the set of data numbers.

A very simple figure of a box and whisker plot you can see below:

Box and Whisker Chart Uses:

  • When you want to observe the upper, lower quartiles, mean, median, deviations, etc. for a large set of data.
  • When you want to see a quick view of the dataset distribution .
  • When you have multiple data sets that come from independent sources and relate to each other in some way.
  • When you need to compare data from different categories.

The table and box-and-whisker plots below shows test scores for Maths and Literature for the same class.

Box and Whisker charts have applications in many scientific areas and types of analysis such as statistical analysis, test results analysis, marketing analysis, data analysis, and etc.

10. Bubble Chart

Bubble charts are super useful types of graphs for making a comparison of the relationships between data in 3 numeric-data dimensions: the Y-axis data, the X-axis data, and data depicting the bubble size.

Bubble charts are very similar to XY Scatter plots but the bubble chart adds more functionality – a third dimension of data that can be extremely valuable.

Both axes (X and Y) of a bubble chart are numeric.

Bubble Chart Uses:

  • When you have to display three or four dimensions of data.
  • When you want to compare and display the relationships between categorized circles, by the use of proportions.

The bubble chart below shows the relationship between Cost (X-Axis), Profit (Y-Axis), and Probability of Success (%) (Bubble Size).

11. Pictographs

The pictograph or a pictogram is one of the more visually appealing types of graphs and charts that display numerical information with the use of icons or picture symbols to represent data sets.

They are very easy to read statistical way of data visualization. A pictogram shows the frequency of data as images or symbols. Each image/symbol may represent one or more units of a given dataset.

Pictograph Uses:

  • When your audience prefers and understands better displays that include icons and illustrations. Fun can promote learning.
  • It’s habitual for infographics to use of a pictogram.
  • When you want to compare two points  in an emotionally powerful way.

The following pictographic represents the number of computers sold by a business company for the period from January to March.

The pictographic example above shows that in January are sold 20 computers (4×5 = 20), in February are sold 30 computers (6×5 = 30) and in March are sold 15 computers.

12. Dot Plot

Dot plot or dot graph is just one of the many types of graphs and charts to organize statistical data. It uses dots to represent data. A Dot Plot is used for relatively small sets of data and the values fall into a number of discrete categories.

If a value appears more than one time, the dots are ordered one above the other. That way the column height of dots shows the frequency for that value.

Dot Plot Uses:

  • To plot frequency counts when you have a small number of categories .
  • Dot plots are very useful when the variable is quantitative or categorical .
  • Dot graphs are also used for univariate data (data with only one variable that you can measure).

Suppose you have a class of 26 students. They are asked to tell their favorite color. The dot plot below represents their choices:

It is obvious that blue is the most preferred color by the students in this class.

13. Radar Chart

A radar chart is one of the most modern types of graphs and charts – ideal for multiple comparisons. Radar charts use a circular display with several different quantitative axes looking like spokes on a wheel. Each axis shows a quantity for a different categorical value.

Radar charts are also known as spider charts, web charts, star plots, irregular polygons, polar charts, cobweb charts or Kiviat diagram.

Radar Chart has many applications nowadays in statistics, maths, business, sports analysis, data intelligence, and etc.

Radar Chart Uses:

  • When you want to observe which variables have similar values or whether there are any outliers amongst each variable.
  • To represent  multiple comparisons .
  • When you want to see which variables are scoring low or high within a dataset. This makes radar chart ideal for displaying performance .

For example, we can compare employee’s performance with the scale of 1-8 on subjects such as Punctuality, Problem-solving, Meeting Deadlines, Marketing Knowledge, Communications. A point that is closer to the center on an axis shows a lower value and a worse performance.

It is obvious that Jane has a better performance than Samanta.

14. Pyramid Graph

When it comes to easy to understand and good looking types of graphs and charts, pyramid graph has a top place.

A pyramid graph is a chart in a pyramid shape or triangle shape. These types of charts are best for data that is organized in some kind of hierarchy. The levels show a progressive order.

Pyramid Graph Uses:

  • When you want to indicate a hierarchy level among the topics or other types of data.
  • Pyramid graph is often used to represent progressive orders such as: “older to newer”, “more important to least important”, “specific to least specific”‘ and etc.
  • When you have a proportional or interconnected relationship between data sets.

A classic pyramid graph example is the healthy food pyramid that shows fats, oils, and sugar (at the top) should be eaten less than many other foods such as vegetables and fruits (at the bottom of the pyramid).

Conclusion:

You might know that choosing the right type of chart is some kind of tricky business.

Anyway, you have a wide choice of types of graphs and charts. Used in the right way, they are a powerful weapon to help you make your reports and presentations both professional and clear.

What are your favorite types of graphs and charts? Share your thoughts on the field below.

About The Author

types of graph representation

Silvia Valcheva

Silvia Valcheva is a digital marketer with over a decade of experience creating content for the tech industry. She has a strong passion for writing about emerging software and technologies such as big data, AI (Artificial Intelligence), IoT (Internet of Things), process automation, etc.

10 Comments

' src=

I have learned a lot from your presentation. Very informative

' src=

Nicely described different graphs, I learned a lot.

' src=

very useful. exiting

' src=

I love this. I learned a lot.

' src=

Very good representation of date. I would suggest an addition of “stem and leaf” diagrams.

' src=

I have only one thing to say and that is this is the best representation of every graphs and charts I have ever seen 😀

' src=

Very well described. Great learning article for beginners on Charts.

' src=

Really helpful thanks

' src=

Very Helpful text; Thanks Silvia Valcheva for your hard work

Leave a Reply Cancel Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed .

Introduction to Graphs

Table of Contents

15 December 2020                 

Read time: 6 minutes

Introduction

What are graphs?

What are the different types of data?

What are the different types of graphical representations?

The graph is nothing but an organized representation of data. It helps us to understand the data. Data are the numerical information collected through observation.

The word data came from the Latin word Datum which means “something given”

After a research question is developed, data is being collected continuously through observation. Then it is organized, summarized, classified, and then represented graphically.

Differences between Data and information: Data is the raw fact without any add on but the information is the meaning derived from data.

Introduction to Graphs-PDF

The graph is nothing but an organized representation of data. It helps us to understand the data. Data are the numerical information collected through observation. Here is a downloadable PDF to explore more.

  • Line and Bar Graphs Application
  • Graphs in Mathematics & Statistics

What are the different Types of Data?

There are two types of Data :

Types of Data

Quantitative

The data which are statistical or numerical are known as Quantitive data. Quantitive data is generated through. Quantitative data is also known as Structured data. Experiments, Tests, Surveys, Market Report.

Quantitive data is again divided into Continuous data and Discrete data.

Continuous Data

Continuous data is the data which can have any value. That means Continuous data can give infinite outcomes so it should be grouped before representing on a graph.

  • The speed of a vehicle as it passes a checkpoint
  • The mass of a cooking apple
  • The time taken by a volunteer to perform a task

Discrete Data

Discrete data can have certain values. That means only a finite number can be categorized as discrete data.

  • Numbers of cars sold at a dealership during a given month
  • Number of houses in certain block
  • Number of fish caught on a fishing trip
  • Number of complaints received at the office of airline on a given day
  • Number of customers who visit at bank during any given hour
  • Number of heads obtained in three tosses of a coin

Differences between Discrete and Continuous data

  • Numerical data could be either discrete or continuous
  • Continuous data can take any numerical value (within a range); For example, weight, height, etc.
  • There can be an infinite number of possible values in continuous data
  • Discrete data can take only certain values by finite ‘jumps’, i.e., it ‘jumps’ from one value to another but does not take any intermediate value between them (For example, number of students in the class)

Qualitative

Data that deals with description or quality instead of numbers are known as Quantitative data. Qualitative data is also known as unstructured data. Because this type of data is loosely compact and can’t be analyzed conventionally.

Different Types of Graphical Representations

There are many types of graph we can use to represent data. They are as follows,

A bar graph or chart is a way to represent data by rectangular column or bar. The heights or length of the bar is proportional to the values.

A bar graph or chart

A line graph is a type of graph where the information or data is plotted as some dots which are known as markers and then they are added to each other by a straight line.

The line graph is normally used to represent the data that changes over time.

A line graph

A histogram graph is a graph where the information is represented along with the height of the rectangular bar. Though it does look like a bar graph, there is a fundamental difference between them. With the histogram, each column represents a range of quantitative data when a bar graph represents categorical variables.

Histogram and Piechart

The other name of the pie chart is a circle graph. It is a circular chart where numerical information represents as slices or in fractional form or percentage where the whole circle is 100%.

Pie chart

  • Stem and leaf plot

The stem and leaf plot is a way to represents quantitative data according to frequency ranges or frequency distribution.

In the stem and leaf plot, each data is split into stem and leaf, which is 32 will be split into 3 stems and 2 leaves.

Stem and leaf plot

Frequency table: Frequency means the number of occurrences of an event. A frequency distribution table is a graph or chart which shows the frequency of events. It is denoted as ‘f’ .

Frequency table

Pictograph or Pictogram is the earliest way to represents data in a pictorial form or by using symbols or images. And each image represents a particular number of things.

Pictograph or Pictogram

According to the above-mentioned Pictograph, the number of Appels sold on Monday is 6x2=12.

  • Scatter diagrams

Scatter diagram or scatter plot is a way of graphical representation by using cartesian coordinates of two variables. The plot shows the relationship between two variables. Below there is a data table as well as a Scattergram as per the given data.

What is the meaning of Graphical representation?

Graphical representation is a way to represent and analyze quantitive data. A graph is a kind of a chart where data are plotted as variables across the coordinate. It became easy to analyze the extent of change of one variable based on the change of other variables.

Principles of graphical representation

The principles of graphical representation are algebraic. In a graph, there are two lines known as Axis or Coordinate axis. These are the X-axis and Y-axis. The horizontal axis is the X-axis and the vertical axis is the Y-axis. They are perpendicular to each other and intersect at O or point of Origin.

On the right side of the Origin, the Xaxis has a positive value and on the left side, it has a negative value. In the same way, the upper side of the Origin Y-axis has a positive value where the down one is with a negative value.

When X-axis and y-axis intersected each other at the origin it divides the plane into four parts which are called Quadrant I, Quadrant II, Quadrant III, Quadrant IV.

Principles of graphical representation

The location on the coordinate plane is known as the ordered pair and it is written as (x,y). That means the first value will be on the x-axis and the second one is on the y-axis. When we will plot any coordinate, we always have to start counting from the origin and have to move along the x-axis, if it is positive then to the right side, and if it is negative then to the left side. Then from the x-axis, we have to plot the y’s value, which means we have to move up for positive value or down if the value is negative along with the y-axis.

In the following graph, 1st ordered pair (2,3) where both the values of x and y are positive and it is on quadrant I. 2nd ordered pair (-3,1), here the value of x is negative and value of y is positive and it is in quadrant II. 3rd ordered pair (-1.5, -2.5), here the value of x as well as y both are Negative and in quadrant III.

Principles of graphical representation

Methods of representing a frequency distribution

There are four methods to represent a frequency distribution graphically. These are,

  • Smoothed Frequency graph
  • Cumulative frequency graph or Ogive.
  • Pie diagram.

Advantages and Disadvantages of Graphical representation of data

  • It improves the way of analyzing and learning as the graphical representation makes the data easy to understand.
  • It can be used in almost all fields from mathematics to physics to psychology and so on.
  • It is easy to understand for its visual impacts.
  • It shows the whole and huge data in an instance.

The main disadvantage of graphical representation of data is that it takes a lot of effort as well as resources to find the most appropriate data and then represents it graphically.

You may also like:

  • Graphing a Quadratic Function
  • Empirical Relationship Between Mean, Median, and Mode

Not only in mathematics but almost in every field the graph is a very important way to store, analyze, and represents information. After any research work or after any survey the next step is to organize the observation or information and plotting them on a graph paper or plane. The visual representation of information makes the understanding of crucial components or trends easier.

A huge amount of data can be store or analyze in a small space.

The graphical representation of data helps to decide by following the trend.

A complete Idea: Graphical representation constitutes a clear and comprehensive idea in the minds of the audience. Reading a large number (say hundreds) of pages may not help to make a decision. Anyone can get a clear idea just by looking into the graph or design.

Graphs are a very conceptual topic, so it is essential to get a complete understanding of the concept. Graphs are great visual aids and help explain numerous things better, they are important in everyday life. Get better at graphs with us, sign up for a free trial . 

About Cuemath

Cuemath, a student-friendly mathematics and coding platform, conducts regular Online Classes for academics and skill-development, and their Mental Math App, on both iOS and Android , is a one-stop solution for kids to develop multiple skills. Understand the Cuemath Fee structure and sign up for a free trial.

Frequently Asked Questions (FAQs)

What is data.

Data are characteristics or information, usually numerical, that are collected through observation.

How do you differentiate between data and information?

Data is the raw fact without any add on but the information is the meaning derived from data.

What are the types of data?

There are two types of Data:

Two types of Data

What are the ways to represent data?

Tables, charts and graphs are all ways of representing data , and they can be used for two broad purposes. The first is to support the collection, organisation and analysis of data as part of the process of a scientific study.

- Tables, charts and graphs are all ways of representing data, and they can be used for two broad purposes. The first is to support the collection, organisation and analysis of data as part of the process of a scientific study.

What are the different types of graphs?

Different types of graphs include:

Learn to Code, Prepare for Interviews, and Get Hired

01 Career Opportunities

  • DSA Roadmap: A to Z Guide to Learn DSA From Scratch

02 Beginner

  • Differences Between Stack and Queue Data Structures
  • Breadth First Search vs Depth First Search
  • Differences Between Array and Linked List
  • Abstract Data Type in Data Structures
  • Priority Queue in Data Structures
  • One dimensional Array in Data Structures with Example
  • Two dimensional Array In Data Structure
  • Multi dimensional array in Data Structures
  • What are Data Structures - Types of Data Structures (Complete Guide)
  • Data Structures and Algorithms
  • Recursion in Data Structures: Recursive Function
  • Complexity Analysis of Data Structures and Algorithms
  • Big O Notation in Data Structures: Time and Space Complexity
  • Arrays in Data Structures - Types, Representation & Algorithm (With Examples)
  • Types of Arrays in Data Structures: 2D, 3D, Jagged Arrays
  • Linked List in Data Structures - Types of Linked Lists & Its Applications
  • Doubly Linked List Algorithm in Data Structures with Examples
  • Implementing Stack in Data Structures
  • Queue in Data Structures - Types & Algorithm (With Example)
  • Searching in Data Structures - Its Types, Methods & Techniques
  • Brute Force Algorithm in Data Structures: Types, Advantages, Disadvantages

03 Intermediate

  • Binary Trees in Data Structures - Types, Implementation, Applications
  • Binary Search Tree in Data Structures
  • Circular Linked Lists in Data Structures
  • What is Linear Search in Data Structures - Its Algorithm, Working, & Complexity
  • Binary Search in Data Structures
  • Sorting in Data Structures - Types of Sorting Algorithms ( With Examples )
  • Bubble Sort in Data Structures
  • Selection Sort in Data Structures
  • Insertion Sort in Data Structures - Algorithm, Working, & Advantages
  • Merge Sort in Data Structures and Algorithms: With Implementation in C++/Java/Python
  • Quick Sort Algorithm in Data Structures - Its Types ( With Examples )
  • Counting Sort in Data Structures
  • Radix Sort in Data Structures - Its Algorithm, Working, & Complexity
  • Bucket Sort in Data Structures
  • Shell Sort in Data Structures - Algorithm, Visualization, & Complexity
  • Divide and Conquer Algorithm in Data Structures - Its Working, Advantages & Disadvantages
  • Greedy Algorithm in Data Structures

04 Advanced

  • Heap in Data Structures
  • Heap Sort Algorithm in Data Structures - Its Working, Implementation & Applications
  • Hashing in Data Structures: Types and Functions [With Examples]
  • Hash Table in Data Structures

Graphs in Data Structures - Types of Graphs, Representation & Operations

  • Breadth First Traversal and Depth First Traversal
  • Spanning Tree and Minimum Spanning Tree in Data Structures - Kruskal's and Prim's Algorithms
  • AVL Tree in Data Structures with Examples
  • Trees in Data Structures - Its Structure, Operations & Applications
  • Segment Tree in Data Structures: Operations, Advantages and Disadvantages
  • Suffix Array and Suffix Tree in Data Structures & Applications
  • K-Dimensional Tree in Data Structures
  • Tower of Hanoi in Data Structures
  • Bellman Ford’s Algorithm in Data Structures - Working, Example and Applications

05 Questions

  • DSA Interview Questions and Answers (Freshers to Experienced)

06 Training Programs

  • Java Programming Course
  • C++ Programming Course
  • Data Structures and Algorithms Training
  • Datastructures
  • Graphs In Data Structures..

Graphs in Data Structures - Types of Graphs, Representation & Operations

Data Structures & Algorithms Free Course

Graphs in data structures: an overview.

Graph in Data Structures is a type of non-primitive and non-linear data structure that consists of a finite set of nodes (or vertices) and a set of edges connecting them. In this DSA tutorial , we will see a detailed starting of the graph concept i.e. its features, types, implementation, etc. To further enhance your understanding and application of graph concepts, consider enrolling in the Dsa Course , where you can gain comprehensive insights into effective data structure utilization for improved problem-solving and time management.

What is a Graph in Data Structures?

A graph is a collection of nodes that consist of data and are connected to other nodes of the graph. formally a Graph is composed of a set of vertices( V ) and a set of edges( E ). The graph is denoted by G(V, E) .

The most common real-life examples of graphs are social media where a User, Photo, Album, Event, Group, Page, Comment, Story, Video, etc represents a node. Every relationship is an edge from one node to another. Whenever you post a photo, join a group, like a page, etc., a new edge is created for that relationship. Thus, it can be said that a social media platform is a collection of nodes and edges.

Graph Terminologies in Data Structures

Graph terminology in data structure refers to the specific vocabulary and concepts used to describe and analyze graphs, which are mathematical structures composed of nodes (also called vertices) connected by edges.

  • Node/Vertex: A fundamental unit of a graph. It represents an entity or an element and is usually depicted as a point.
  • Edge/Arc: A connection between two nodes. It represents a relationship or a link between the corresponding entities. An edge can be directed (arc), indicating a one-way connection, or undirected, representing a two-way connection.
  • Adjacent Nodes: Two nodes that are directly connected by an edge. In an undirected graph, both nodes are considered adjacent to each other. In a directed graph, adjacency depends on the direction of the edge.
  • Degree: The degree of a node is the number of edges incident to it, i.e., the number of edges connected to that node. In a directed graph, the degree is divided into two categories: the in-degree (number of incoming edges) and the out-degree (number of outgoing edges).
  • Path: A path in a graph is a sequence of edges that connects a sequence of nodes. It can be a simple path (no repeated nodes) or a closed path/cycle (starts and ends at the same node).
  • Bipartite Graph: A graph whose nodes can be divided into two disjoint sets such that every edge connects a node from one set to a node from the other set. In other words, there are no edges between nodes within the same set.
  • Spanning Tree: A subgraph of a connected graph that includes all the nodes of the original graph and forms a tree (a connected acyclic graph) by eliminating some of the edges.
  • Cycle: A closed path in a graph, where the first and last nodes are the same. It consists of at least three edges.

Read More - Best Data Structure Interview Questions and Answers

Types of Graphs in Data Structures

Finite graph.

If the graph, G=(V, E) has a finite number of edges and vertices, it is a finite graph. In other words, both the number of vertices and the number of edges in a finite graph are limited and can be counted.

Finite Graph

Infinite Graph

If the graph G=(V, E) has an infinite number of edges and vertices, it is an infinite graph.

Infinite Graph

Trivial Graph

If a finite graph G=(V, E) has just one vertex and no edges, it is referred to as trivial. It is also known as a singleton graph or a single vertex graph.

Trivial Graph

Simple Graph

A graph G=(V, E) is a simple one if each pair of nodes or vertices contains just one edge. In order to represent one-to-one interactions between two elements, there is only one edge connecting two vertices.

Simple Graph

Multi Graph

A graph G=(V, E) is referred to as a multigraph if it has some parallel edges between two vertices but doesn't contain any self-loop. An edge of a graph that starts from a vertex and ends at the same vertex is called a loop or a self-loop.

Multi Graph

It's a revised version of a trivial graph. A graph G=(V, E) is a null graph if it has many vertices but none of them are connected by any edges. A null graph can also be referred to as an edgeless graph, an isolated graph, or a discrete graph.

Null Graph

Complete Graph

A simple graph G=(V, E) with n vertices is also called a complete graph if the degree of each vertex is n-1, i.e. one vertex is attached with n-1 edges or the rest of the vertices in the graph. A complete graph is also called a Full Graph.

Complete Graph

Pseudo Graph

A pseudograph exists when a graph G= (V, E) contains some self-loop in addition to some multiple edges.

Pseudo Graph

Regular Graph

Regular Graph

Weighted Graph

A graph G=(V, E) in which edges have weights or costs associated with them is a weighted graph.

Weighted Graph

Directed Graph

A directed graph, also known as a digraph, is a collection of nodes connected by edges, each with a distinct direction.

Directed Graph

Undirected Graph

A graph G=(V, E) in which edges have no direction, i.e., the edges do not have arrows indicating the direction of traversal is an undirected graph.

Undirected Graph

Connected Graph

A graph G = (V, E) is said to be connected if there exists at least one path between each and every pair of vertices in the graph.

Connected Graph

Disconnected Graph

If in a graph G = (V, E), there does not exist any path between at least one pair of vertices, it is a disconnected graph. A null graph with n vertices is a disconnected graph.

Disconnected Graph

Cyclic Graph

A graph is termed cyclic if it forms at least one cycle.

Cyclic Graph

Acyclic Graph

A graph is said to be acyclic if it contains no cycles.

Acyclic Graph

Directed Acyclic Graph

It is a graph with directed edges but no cycle.

Directed Acyclic Graph

A subgraph is a set of vertices and edges in one graph that are subsets of another.

Subgraph

Graph Representation in Data Structures

  • Graph representation is a way of structuring and visualizing data using nodes (vertices) and edges. It is a technique to store graphs in the memory of a computer.
  • In a graph, nodes represent individual entities, while edges represent the relationships or connections between those entities. The connections can be directional or undirected, depending on whether the edges have a specific direction or not.

There are two ways to represent a graph

Adjacency Matrix

An Adjacency Matrix is a 2D array of size V x V where V is the number of nodes in a graph. It is used to represent a finite graph, with 0's and 1's. Since it's a V x V matrix, it is known as a square matrix. The elements of the matrix indicate whether pairs of vertices are adjacent or not in the graph i.e. if there is any edge connecting a pair of nodes in the graph.

Representation of Undirected Graph

Representation of Undirected Graph

Representation of a Directed Graph

Representation of a Directed Graph

Weighted Undirected Graph Representation

A weighted graph representing these values in the matrix is indicated at the graph's edge.

Weighted Undirected Graph Representation

  • Adjacency List

An adjacency list represents a graph as an array of linked lists . The index of the array represents a vertex and each element in its linked list represents the other vertices that form an edge with the vertex.

Weighted Undirected Graph Representation Using Linked-List

Weighted Undirected Graph Representation Using Linked-List

Weighted Undirected Graph Representation Using an Array

Weighted Undirected Graph Representation Using an Array

Operations on Graphs in Data Structures

The following common operations are performed on graphs in data structures:

Insert vertex

It is a simple addition of a vertex(node) in a graph. It need not be connected to any other vertex(node) through an edge.

Insert vertex

Delete vertex

To delete a nod, we also have to remove all the edges associated with that vertex.

Delete vertex

Insert Edge

It adds an edge between a pair of vertices.

Insert Edge

Delete Edge

An edge can be deleted by severing the link between its vertices or nodes. If all the edges from a particular vertex(node) are removed, then that vertex(node) becomes an isolated vertex.

Delete Edge

Graph Traversal

Graph traversal is the process of going through or updating each vertex in a graph. Such traversals are classified according to the order in which the algorithm visits the vertices. A subset of tree traversal is graph traversal.

There are two algorithms/ways to visit a graph:

  • Breadth-first search
  • Depth-first search

We will study all these two in the section Breadth First Traversal and Depth First Traversal

Application of Graphs

  • Maps GPS Systems can be represented using graphs and then can be used by computers to provide various services.
  • When various tasks depend on each other, it can be represented using a Directed Acyclic graph and we can find the order in which tasks can be performed using topological sort.
  • State Transition Diagram represents what can be the legal moves from current states.
  • Graphs can be used to represent the topology of computer networks, such as the connections between routers and switches.

Advantages of Graphs

  • Graphs can be used to represent a wide range of relationships and data structures.
  • They can be used to model and solve a wide range of problems, including pathfinding, data clustering, network analysis, and machine learning.
  • Graph algorithms are often very efficient and can be used to solve complex problems quickly and effectively.
  • They can be used to represent complex data structures simply and intuitively, making them easier to understand and analyze.

Disadvantages of Graphs

  • Graphs can be complex and difficult to understand, especially for people not familiar with graph theory or related algorithms.
  • Creating and manipulating graphs can be computationally expensive, especially very large or complex graphs.
  • Graph algorithms can be difficult to design and implement correctly and can be prone to bugs and errors.
  • Graphs can be difficult to visualize and analyze, especially for very large or complex graphs, which can make it challenging to extract meaningful insights from the data.

So, here we saw a detailed introduction to graphs in data structures. You might have got at least some idea regarding graphs and their applications. We will cover all its aspects one by one in the upcoming tutorials. To also gain a practical understanding of graphs, enroll in our Best Dsa Course .

Q1. What is a path in a graph?

Q2. what is meant by degree of a node in a graph, q3. what are the two ways to represent a graph.

  • Adjacency Matrix 

Live Classes Schedule

Can't find convenient schedule? Let us know

About Author

Author image

We use cookies to make interactions with our websites and services easy and meaningful. Please read our Privacy Policy for more details.

  • Data Structures
  • Linked List
  • Binary Tree
  • Binary Search Tree
  • Segment Tree
  • Disjoint Set Union
  • Fenwick Tree
  • Red-Black Tree
  • Advanced Data Structures
  • Graph Data Structure And Algorithms
  • Introduction to Graphs - Data Structure and Algorithm Tutorials
  • Graph and its representations

Types of Graphs with Examples

  • Basic Properties of a Graph
  • Applications, Advantages and Disadvantages of Graph
  • Transpose graph
  • Difference Between Graph and Tree

BFS and DFS on Graph

  • Breadth First Search or BFS for a Graph
  • Depth First Search or DFS for a Graph
  • Applications, Advantages and Disadvantages of Depth First Search (DFS)
  • Applications, Advantages and Disadvantages of Breadth First Search (BFS)
  • Iterative Depth First Traversal of Graph
  • BFS for Disconnected Graph
  • Transitive Closure of a Graph using DFS
  • Difference between BFS and DFS

Cycle in a Graph

  • Detect Cycle in a Directed Graph
  • Detect cycle in an undirected graph
  • Detect Cycle in a directed graph using colors
  • Detect a negative cycle in a Graph | (Bellman Ford)
  • Cycles of length n in an undirected and connected graph
  • Detecting negative cycle using Floyd Warshall
  • Clone a Directed Acyclic Graph

Shortest Paths in Graph

  • How to find Shortest Paths from Source to all Vertices using Dijkstra's Algorithm
  • Bellman–Ford Algorithm
  • Floyd Warshall Algorithm
  • Johnson's algorithm for All-pairs shortest paths
  • Shortest Path in Directed Acyclic Graph
  • Multistage Graph (Shortest Path)
  • Shortest path in an unweighted graph
  • Karp's minimum mean (or average) weight cycle algorithm
  • 0-1 BFS (Shortest Path in a Binary Weight Graph)
  • Find minimum weight cycle in an undirected graph

Minimum Spanning Tree in Graph

  • Kruskal’s Minimum Spanning Tree (MST) Algorithm
  • Difference between Prim's and Kruskal's algorithm for MST
  • Applications of Minimum Spanning Tree
  • Total number of Spanning Trees in a Graph
  • Minimum Product Spanning Tree
  • Reverse Delete Algorithm for Minimum Spanning Tree

Topological Sorting in Graph

  • Topological Sorting
  • All Topological Sorts of a Directed Acyclic Graph
  • Kahn's algorithm for Topological Sorting
  • Maximum edges that can be added to DAG so that it remains DAG
  • Longest Path in a Directed Acyclic Graph
  • Topological Sort of a graph using departure time of vertex

Connectivity of Graph

  • Articulation Points (or Cut Vertices) in a Graph
  • Biconnected Components
  • Bridges in a graph
  • Eulerian path and circuit for undirected graph
  • Fleury's Algorithm for printing Eulerian Path or Circuit
  • Strongly Connected Components
  • Count all possible walks from a source to a destination with exactly k edges
  • Euler Circuit in a Directed Graph
  • Word Ladder (Length of shortest chain to reach a target word)
  • Find if an array of strings can be chained to form a circle | Set 1
  • Tarjan's Algorithm to find Strongly Connected Components
  • Paths to travel each nodes using each edge (Seven Bridges of Königsberg)
  • Dynamic Connectivity | Set 1 (Incremental)

Maximum flow in a Graph

  • Max Flow Problem Introduction
  • Ford-Fulkerson Algorithm for Maximum Flow Problem
  • Find maximum number of edge disjoint paths between two vertices
  • Find minimum s-t cut in a flow network
  • Maximum Bipartite Matching
  • Channel Assignment Problem
  • Introduction to Push Relabel Algorithm
  • Introduction and implementation of Karger's algorithm for Minimum Cut
  • Dinic's algorithm for Maximum Flow

Some must do problems on Graph

  • Find size of the largest region in Boolean Matrix
  • Count number of trees in a forest
  • A Peterson Graph Problem
  • Clone an Undirected Graph
  • Introduction to Graph Coloring
  • Traveling Salesman Problem (TSP) Implementation
  • Introduction and Approximate Solution for Vertex Cover Problem
  • Erdos Renyl Model (for generating Random Graphs)
  • Chinese Postman or Route Inspection | Set 1 (introduction)
  • Hierholzer's Algorithm for directed graph
  • Boggle (Find all possible words in a board of characters) | Set 1
  • Hopcroft–Karp Algorithm for Maximum Matching | Set 1 (Introduction)
  • Construct a graph from given degrees of all vertices
  • Determine whether a universal sink exists in a directed graph
  • Number of sink nodes in a graph
  • Two Clique Problem (Check if Graph can be divided in two Cliques)
A Graph is a non-linear data structure consisting of nodes and edges . The nodes are sometimes also referred to as vertices and the edges are lines or arcs that connect any two nodes in the graph. More formally a Graph can be defined as, A Graph consisting of a finite set of vertices(or nodes) and a set of edges that connect a pair of nodes
  • Undirected Graphs : A graph in which edges have no direction, i.e., the edges do not have arrows indicating the direction of traversal. Example: A social network graph where friendships are not directional.
  • Directed Graphs : A graph in which edges have a direction, i.e., the edges have arrows indicating the direction of traversal. Example: A web page graph where links between pages are directional.
  • Weighted Graphs: A graph in which edges have weights or costs associated with them. Example: A road network graph where the weights can represent the distance between two cities.
  • Unweighted Graph s: A graph in which edges have no weights or costs associated with them. Example: A social network graph where the edges represent friendships.
  • Complete Graphs: A graph in which each vertex is connected to every other vertex. Example: A tournament graph where every player plays against every other player.
  • Bipartite Graphs: A graph in which the vertices can be divided into two disjoint sets such that every edge connects a vertex in one set to a vertex in the other set. Example: A job applicant graph where the vertices can be divided into job applicants and job openings.
  • Trees : A connected graph with no cycles. Example: A family tree where each person is connected to their parents.
  • Cycles : A graph with at least one cycle. Example: A bike-sharing graph where the cycles represent the routes that the bikes take.
  • Sparse Graphs: A graph with relatively few edges compared to the number of vertices. Example: A chemical reaction graph where each vertex represents a chemical compound and each edge represents a reaction between two compounds.
  • Dense Graph s: A graph with many edges compared to the number of vertices. Example: A social network graph where each vertex represents a person and each edge represents a friendship.

Types of Graphs:

1. finite graphs.

 A graph is said to be finite if it has a finite number of vertices and a finite number of edges. A finite graph is a graph with a finite number of vertices and edges. In other words, both the number of vertices and the number of edges in a finite graph are limited and can be counted. Finite graphs are often used to model real-world situations, where there is a limited number of objects and relationships between the

types of graph representation

2. Infinite Graph:  

A graph is said to be infinite if it has an infinite number of vertices as well as an infinite number of edges. 

types of graph representation

3. Trivial Graph:  

A graph is said to be trivial if a finite graph contains only one vertex and no edge. A trivial graph is a graph with only one vertex and no edges. It is also known as a singleton graph or a single vertex graph. A trivial graph is the simplest type of graph and is often used as a starting point for building more complex graphs. In graph theory, trivial graphs are considered to be a degenerate case and are not typically studied in detail

types of graph representation

4. Simple Graph:

A simple graph is a graph that does not contain more than one edge between the pair of vertices. A simple railway track connecting different cities is an example of a simple graph. 

types of graph representation

5. Multi Graph:

Any graph which contains some parallel edges but doesn’t contain any self-loop is called a multigraph. For example a Road Map. 

  • Parallel Edges: If two vertices are connected with more than one edge then such edges are called parallel edges that are many routes but one destination.
  • Loop: An edge of a graph that starts from a vertex and ends at the same vertex is called a loop or a self-loop.

types of graph representation

6. Null Graph:

A graph of order n and size zero is a graph where there are only isolated vertices with no edges connecting any pair of vertices.A null graph is a graph with no edges. In other words, it is a graph with only vertices and no connections between them. A null graph can also be referred to as an edgeless graph, an isolated graph, or a discrete graph

types of graph representation

7. Complete Graph:

A simple graph with n vertices is called a complete graph if the degree of each vertex is n-1, that is, one vertex is attached with n-1 edges or the rest of the vertices in the graph. A complete graph is also called Full Graph. 

types of graph representation

8. Pseudo Graph:

A graph G with a self-loop and some multiple edges is called a pseudo graph. A pseudograph is a type of graph that allows for the existence of self-loops (edges that connect a vertex to itself) and multiple edges (more than one edge connecting two vertices). In contrast, a simple graph is a graph that does not allow for loops or multiple edges. 

types of graph representation

9. Regular Graph:

A simple graph is said to be regular if all vertices of graph G are of equal degree. All complete graphs are regular but vice versa is not possible. A regular graph is a type of undirected graph where every vertex has the same number of edges or neighbors. In other words, if a graph is regular, then every vertex has the same degree. 

types of graph representation

10. Bipartite Graph:

A graph G = (V, E) is said to be a bipartite graph if its vertex set V(G) can be partitioned into two non-empty disjoint subsets. V1(G) and V2(G) in such a way that each edge e of E(G) has one end in V1(G) and another end in V2(G). The partition V1 U V2 = V is called Bipartite of G. Here in the figure: V1(G)={V5, V4, V3} and V2(G)={V1, V2} 

types of graph representation

11. Labeled Graph:

If the vertices and edges of a graph are labeled with name, date, or weight then it is called a labeled graph. It is also called Weighted Graph. 

types of graph representation

12. Digraph Graph:

A graph G = (V, E) with a mapping f such that every edge maps onto some ordered pair of vertices (Vi, Vj) are called a Digraph. It is also called Directed Graph . The ordered pair (Vi, Vj) means an edge between Vi and Vj with an arrow directed from Vi to Vj. Here in the figure: e1 = (V1, V2) e2 = (V2, V3) e4 = (V2, V4) 

types of graph representation

13. Subgraph:

A graph G1 = (V1, E1) is called a subgraph of a graph G(V, E) if V1(G) is a subset of V(G) and E1(G) is a subset of E(G) such that each edge of G1 has same end vertices as in G. 

types of graph representation

14. Connected or Disconnected Graph:

Graph G is said to be connected if any pair of vertices (Vi, Vj) of a graph G is reachable from one another. Or a graph is said to be connected if there exists at least one path between each and every pair of vertices in graph G, otherwise, it is disconnected. A null graph with n vertices is a disconnected graph consisting of n components. Each component consists of one vertex and no edge. 

types of graph representation

15. Cyclic Graph:

A graph G consisting of n vertices and n> = 3 that is V1, V2, V3- – – – Vn and edges (V1, V2), (V2, V3), (V3, V4)- – – – (Vn, V1) are called cyclic graph. 

types of graph representation

16. Types of Subgraphs:

  • Vertex disjoint subgraph: Any two graph G1 = (V1, E1) and G2 = (V2, E2) are said to be vertex disjoint of a graph G = (V, E) if V1(G1) intersection V2(G2) = null. In the figure, there is no common vertex between G1 and G2.
  • Edge disjoint subgraph: A subgraph is said to be edge-disjoint if E1(G1) intersection E2(G2) = null. In the figure, there is no common edge between G1 and G2.

Note: Edge disjoint subgraph may have vertices in common but a vertex disjoint graph cannot have a common edge, so the vertex disjoint subgraph will always be an edge-disjoint subgraph.

17. Spanning Subgraph

Consider the graph G(V,E) as shown below. A spanning subgraph is a subgraph that contains all the vertices of the original graph G that is G'(V’,E’) is spanning if V’=V and E’ is a subset of E.

types of graph representation

So one of the spanning subgraph can be as shown below G'(V’,E’). It has all the vertices of the original graph G and some of the edges of G.

types of graph representation

This is just one of the many spanning subgraphs of graph G. We can create various other spanning subgraphs by different combinations of edges. Note that if we consider a graph G'(V’,E’) where V’=V and E’=E, then graph G’ is a spanning subgraph of graph G(V,E).

Advantages of graphs:

  • Graphs can be used to model and analyze complex systems and relationships.
  • They are useful for visualizing and understanding data.
  • Graph algorithms are widely used in computer science and other fields, such as social network analysis, logistics, and transportation.
  • Graphs can be used to represent a wide range of data types, including social networks, road networks, and the internet.

Disadvantages of graphs:

  • Large graphs can be difficult to visualize and analyze.
  • Graph algorithms can be computationally expensive, especially for large graphs.
  • The interpretation of graph results can be subjective and may require domain-specific knowledge.
  • Graphs can be susceptible to noise and outliers, which can impact the accuracy of analysis results.

Related article: Applications, Advantages and Disadvantages of Graph

Please Login to comment...

Similar reads.

  • Mathematical

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

All Courses

  • Interview Questions
  • Free Courses
  • Career Guide
  • PGP in Data Science and Business Analytics
  • PG Program in Data Science and Business Analytics Classroom
  • PGP in Data Science and Engineering (Data Science Specialization)
  • PGP in Data Science and Engineering (Bootcamp)
  • PGP in Data Science & Engineering (Data Engineering Specialization)
  • Master of Data Science (Global) – Deakin University
  • MIT Data Science and Machine Learning Course Online
  • Master’s (MS) in Data Science Online Degree Programme
  • MTech in Data Science & Machine Learning by PES University
  • Data Analytics Essentials by UT Austin
  • Data Science & Business Analytics Program by McCombs School of Business
  • MTech In Big Data Analytics by SRM
  • M.Tech in Data Engineering Specialization by SRM University
  • M.Tech in Big Data Analytics by SRM University
  • PG in AI & Machine Learning Course
  • Weekend Classroom PG Program For AI & ML
  • AI for Leaders & Managers (PG Certificate Course)
  • Artificial Intelligence Course for School Students
  • IIIT Delhi: PG Diploma in Artificial Intelligence
  • Machine Learning PG Program
  • MIT No-Code AI and Machine Learning Course
  • Study Abroad: Masters Programs
  • MS in Information Science: Machine Learning From University of Arizon
  • SRM M Tech in AI and ML for Working Professionals Program
  • UT Austin Artificial Intelligence (AI) for Leaders & Managers
  • UT Austin Artificial Intelligence and Machine Learning Program Online
  • MS in Machine Learning
  • IIT Roorkee Full Stack Developer Course
  • IIT Madras Blockchain Course (Online Software Engineering)
  • IIIT Hyderabad Software Engg for Data Science Course (Comprehensive)
  • IIIT Hyderabad Software Engg for Data Science Course (Accelerated)
  • IIT Bombay UX Design Course – Online PG Certificate Program
  • Online MCA Degree Course by JAIN (Deemed-to-be University)
  • Cybersecurity PG Course
  • Online Post Graduate Executive Management Program
  • Product Management Course Online in India
  • NUS Future Leadership Program for Business Managers and Leaders
  • PES Executive MBA Degree Program for Working Professionals
  • Online BBA Degree Course by JAIN (Deemed-to-be University)
  • MBA in Digital Marketing or Data Science by JAIN (Deemed-to-be University)
  • Master of Business Administration- Shiva Nadar University
  • Post Graduate Diploma in Management (Online) by Great Lakes
  • Online MBA Programs
  • Cloud Computing PG Program by Great Lakes
  • University Programs
  • Stanford Design Thinking Course Online
  • Design Thinking : From Insights to Viability
  • PGP In Strategic Digital Marketing
  • Post Graduate Diploma in Management
  • Master of Business Administration Degree Program
  • MS in Business Analytics in USA
  • MS in Machine Learning in USA
  • Study MBA in Germany at FOM University
  • M.Sc in Big Data & Business Analytics in Germany
  • Study MBA in USA at Walsh College
  • MS Data Analytics
  • MS Artificial Intelligence and Machine Learning
  • MS in Data Analytics
  • Master of Business Administration (MBA)
  • MS in Information Science: Machine Learning
  • MS in Machine Learning Online
  • MS in Computer Science
  • MS in Computer Science and MS in Data Analytics
  • MIT Data Science Program
  • AI For Leaders Course
  • Data Science and Business Analytics Course
  • Cyber Security Course
  • PG Program Online Artificial Intelligence Machine Learning
  • PG Program Online Cloud Computing Course
  • Data Analytics Essentials Online Course
  • MIT Programa Ciencia De Dados Machine Learning
  • MIT Programa Ciencia De Datos Aprendizaje Automatico
  • Program PG Ciencia Datos Analitica Empresarial Curso Online
  • Mit Programa Ciencia De Datos Aprendizaje Automatico
  • Online Data Science Business Analytics Course
  • Online Ai Machine Learning Course
  • Online Full Stack Software Development Course
  • Online Cloud Computing Course
  • Cybersecurity Course Online
  • Online Data Analytics Essentials Course
  • Ai for Business Leaders Course
  • Mit Data Science Program
  • No Code Artificial Intelligence Machine Learning Program
  • MS Information Science Machine Learning University Arizona
  • Wharton Online Advanced Digital Marketing Program
  • Graph Basics
  • What Is A Graph?
  • Major Graph Terminology
  • Methods Of Graph Operations
  • Representation Of Graphs
  • Types of Graphs

Representing Graphs in Data Structures

Contributed by: Ruchi Nayyar

Graphs are fundamental data structures widely used to model relationships between objects. 

Whether it’s social networks, transportation systems, or computer networks, graphs are powerful tools for representing connections and dependencies. 

In computer science, understanding how to represent graphs efficiently is crucial for solving complex problems effectively. 

In this blog post, we will explore the representation of graphs in data structures and explain the various representations of graphs with detailed examples that will help you understand the concept. 

A graph is a fundamental construct in computer science. It serves as an abstract representation of interconnected objects. 

It comprises two main components: vertices, which represent the objects, and edges, which denote the links between them.

A graph is a pair of sets (V, E), where V represents the vertices and E the edges connecting these vertices.

For instance, consider the following graph:

Graph Basics:

  • V = {a, b, c, d, e}
  • E = {ab, ac, bd, cd, de}

Graph illustration

In this graph, the vertices are {a, b, c, d, e}, and the edges are {ab, ac, bd, cd, de}. Each edge connects two vertices, indicating a relationship between them.

Understanding the concept of a graph is crucial for various applications. It forms the cornerstone of graph representation in data structures, enabling efficient manipulation and analysis of interconnected data.

Don’t miss out on the opportunity to enroll in the ‘ Free Data Structures in C Course ‘ and build a strong foundation in programming.

Read “ What is Data Structure: Need, Types & Classification ” to enhance your comprehension of data structuring fundamentals and their significance!

Understanding the major terminology associated with graphs is essential for navigating through graph-related concepts effectively:

  • Vertex- Also known as a node, a vertex represents an entity within a graph. It can represent various things, such as cities in a transportation network or users in a social media platform.
  • Edge- An edge represents a graph’s connection or relationship between two vertices. It can be directional (from one vertex to another) or undirected (connecting two vertices without a specific direction).
  • Adjacency- Adjacency refers to the relationship between vertices directly connected by an edge. For example, if vertex A is connected to vertex B by an edge, then A and B are considered adjacent.
  • Path- A path in a graph is a sequence of vertices connected by edges. It represents a route or journey from one vertex to another. Paths can be simple (no repeated vertices) or cyclic (repeating vertices).
  • Directed Graph- Also known as a digraph, a directed graph is a type of graph in which edges have a direction. This means that the relationship between vertices is one-way, indicating a specific direction for traversal. 

Understanding these fundamental concepts lays the foundation for exploring more advanced graph representation techniques, algorithms, and applications.

Don’t miss out on the insights presented in “ Application of Graph Theory in 2024 ” to understand graph theory’s impact on today’s world.

1. Depth First Search Traversal (DFS)

DFS is a graph traversal algorithm that systematically explores all vertices by going as deep as possible along each branch before backtracking.

It starts from an arbitrary vertex, explores as far as possible along each branch before backtracking, and continues until all vertices are visited. DFS utilizes a stack data structure to keep track of vertices.

2. Breadth First Search Traversal (BFS)

BFS is a graph traversal algorithm that systematically explores all vertices at the current level before moving to the next level. 

It starts from an arbitrary vertex, explores all adjacent vertices at the current level, and then moves to the next level. BFS utilizes a queue data structure to keep track of vertices.

3. Detecting Cycles

Detecting cycles in a graph involves identifying if there are any loops or cycles present within the graph structure. 

This is crucial in various applications to prevent infinite loops or unintended behavior. Techniques like depth-first or breadth-first search can detect cycles by keeping track of visited vertices and identifying back edges during traversal.

4. Topological Sorting

Topological sorting is a graph algorithm used to linearly order the vertices of a directed acyclic graph (DAG) based on their dependencies. 

It ensures that for every directed edge from vertex u to vertex v, u comes before v in the ordering. Topological sorting is commonly used in scheduling tasks, resolving dependencies in build systems, and optimizing workflow execution.

5. Minimum Spanning Tree (MST)

A Minimum Spanning Tree (MST) is a subset of edges of a connected, undirected graph that connects all vertices with the minimum possible total edge weight. 

Finding a graph’s MST is essential in various applications, such as network design, clustering, and resource allocation. Common algorithms for finding MST include Kruskal’s algorithm and Prim’s algorithm.

Graphs can be represented in different ways, each offering unique advantages and trade-offs in terms of space complexity, time complexity, and ease of implementation. 

Two different ways of representing a graph in data structure are the Adjacency Matrix and Adjacency List.

1. Adjacency Matrix

An adjacency matrix is a 2D array in which each cell represents the presence or absence of an edge between two vertices. If an edge exists from vertex i to vertex j, the cell (i, j) contains a non-zero value (often 1); otherwise, it includes 0.

  • Straightforward Implementation- The adjacency matrix is intuitive and easy to implement. It directly translates the graph structure into a matrix.
  • Efficient for Dense Graphs- In graphs where the number of edges is close to the maximum possible (dense graphs), adjacency matrices are efficient as they use less memory than lists.
  • Constant-Time Access- This method determines if an edge between two vertices is constant-time (O(1)), making it efficient for certain operations like checking for connectivity.

Disadvantages

  • Memory Consumption- Adjacency matrices consume more memory, especially for sparse graphs, where many entries in the matrix are zero.
  • Inefficiency for Sparse Graphs- Adjacency matrices are inefficient in graphs with few edges (sparse graphs) because they waste memory storing zero values.
  • Inflexible for Dynamic Graphs- Modifying the graph structure, such as adding or removing edges, can be inefficient as it requires resizing the matrix.

Example Consider the following graph with vertices A, B, C, and D:

In this adjacency matrix, a value of 1 indicates the presence of an edge between the corresponding vertices, while 0 indicates no edge. Lets understand better with code

Code Example

Output : Adjacency Matrix

Adjacency Matrix Code Explanation

The code defines a graph class that represents a graph using an adjacency matrix. It initializes with the number of vertices and creates a 2D array to store edges. 

The add_edge method updates the matrix to indicate the presence of an edge between vertices. The display method prints the adjacency matrix. 

The example creates a graph with 4 vertices, adds edges, and displays the adjacency matrix. The output shows the matrix representing the graph structure.

Apart from python, If you’re seeking insights into how data structures operate in C, delve into “ Data Structures using C | What are the Data Structure in C and How it works? “

2. Adjacency List

An adjacency list is a collection of linked lists or arrays, each representing a vertex in the graph. Each element in the list/array stores the adjacent vertices of the corresponding vertex.

  • Memory Efficiency for Sparse Graphs- Adjacency lists are memory-efficient for sparse graphs since they only store information about existing edges.
  • Efficient for Dynamic Graphs- Adjacency lists are suitable for dynamic graphs where edges are frequently added or removed, as they can be easily modified without resizing.
  • Efficient Traversal- Traversal of adjacent vertices is efficient as each vertex maintains a list of its adjacent vertices.
  • Complex Implementation- Implementing adjacency lists requires managing linked lists or arrays for each vertex, which can be more complicated than an adjacency matrix.
  • Potential Additional Memory Usage- Depending on the implementation, adjacency lists may require additional memory for storing pointers or references to adjacent vertices.

Consider the same graph with vertices A, B, C, and D:

Each vertex is associated with a list/array containing its adjacent vertices in this adjacency list representation. For example, vertex A is adjacent to vertices B and C, as the list indicates [B, C]. Lets understand this better with the code

Output : Adjacency List

Adjacency List Code Explanation

The code defines a graph class that represents a graph using an adjacency list. It initializes an empty dictionary to store vertices and their adjacent vertices. 

The add_edge method adds vertices and their neighbors to the adjacency list. The display method prints the adjacency list. 

The example creates a graph, adds edges, and displays the adjacency list. The output shows each vertex and its adjacent vertices.

Understanding the various representations of graphs in data structures is crucial for efficiently storing and traversing graphs, enabling the implementation of various algorithms and analyses.

You can also Checkout our blog on ‘ Data Structures and Algorithms in Java ‘ to become a Java expert in Data Structures and Algorithms

Graphs can be classified into various types based on their characteristics and properties. Two common types are Directed Graphs (Digraphs) and Undirected Graphs.

1. Directed Graph (Digraph)

In a directed graph, edges have a direction associated with them. This means that the relationship between vertices is one-way, indicating a specific direction for traversal.

Characteristics

  • Directional Edges- Each edge in the graph has a direction from one vertex to another, indicating a specific relationship between them.
  • Asymmetric Relationships- The relationship between vertices in a directed graph is asymmetric, meaning that the presence of an edge from vertex A to vertex B does not necessarily imply the existence of an edge from B to A.
  • Directed Connectivity- Directed graphs can represent various relationships with specific directional dependencies.

Applications

  • Network Routing- Directed graphs are used in network routing algorithms to model the flow of data or resources through a network with specific directional paths.
  • Dependency Analysis- In software engineering, directed graphs are utilized for dependency analysis, where dependencies between components or modules are represented with directional edges.
  • Social Networks- Directed graphs can model social networks, where edges represent inherently directional relationships such as following or subscribing.

Directed Graph Representation

Visualization of the directed graph with vertices A, B, and C connected by directed edges indicating the direction of relationships.

Explanation

The code creates a directed graph with three nodes (A, B, and C) and three edges forming a cycle: An edge from A to B. An edge from B to C. An edge from C to A. The graph is then visualized with arrows indicating the direction of the edges, and node labels are displayed. The resulting graph is a simple directed cycle.

Join our Post Graduate Program in Data Science and Business Analytics and learn the essentials of data structure, including representing graphs.  – Get a Dual Certificate from UT Austin & Great Lakes – Learn anytime, anywhere – Weekly online mentorship by experts – Dedicated Program Support

2. Undirected Graph

In an undirected graph, edges do not have a direction associated with them. This means that the relationship between vertices is bidirectional, allowing traversal in both directions.

  • Undirected Edges- Edges in the graph do not have a specific direction associated with them, allowing traversal in both directions between connected vertices.
  • Symmetric Relationships- The relationship between vertices in an undirected graph is symmetric, meaning that if there is an edge between vertices A and B, there is also an edge between vertices B and A.
  • Bidirectional Connectivity- Undirected graphs represent bidirectional relationships where the order of vertices does not matter.
  • Social Networks- Undirected graphs are commonly used to model social networks, where friendships or connections between individuals are inherently bidirectional.
  • Transportation Networks- Undirected graphs can represent transportation networks, where edges represent connections between locations or nodes without specifying a direction of travel.
  • Wireless Sensor Networks- Undirected graphs are utilized in wireless sensor networks to model bidirectional communication links between sensor nodes.

Undirected Graph Representation

The code creates an undirected graph with three nodes (A, B, and C) and three edges forming a cycle: An edge between A and B. An edge between B and C. An edge between C and A. The graph is visualized with node labels displayed. Since it is an undirected graph, the edges do not have arrows indicating direction, representing a simple cycle connecting the three nodes.

Don’t miss out on “ Data Structures For Beginners ” – the perfect starting point for understanding the core concepts of data organization.

Understanding the various methods of representing graphs in data structures is essential for effective problem-solving in fields like data science and business analytics . 

Just as graphs are powerful tools for modelling relationships between objects, mastering their representation allows for efficient manipulation and analysis of interconnected data. 

With the Great Learning Post Graduate Program in Data Science and Business Analytic s, offering dual certification from UT Austin & Great Lakes, learners gain the necessary skills and knowledge to tackle complex graph-related challenges. 

Through any time, anywhere learning and weekly online mentorship by experts, coupled with dedicated program support, participants can confidently navigate the intricate world of graph representation, paving the way for success in their professional endeavors.

The choice between an adjacency matrix and an adjacency list depends on factors such as the density of the graph, memory constraints, and the operations to be performed on it. Sparse graphs are typically better represented using adjacency lists due to their memory efficiency, while dense graphs may benefit from adjacency matrices for faster edge lookup.

Optimizing graph representations for large-scale datasets involves techniques such as parallel processing, distributed computing, and graph partitioning. By leveraging scalable data structures and algorithms, learners can handle massive graphs efficiently, enabling analysis of complex networks and systems.

For dynamic graphs, consider using data structures like dynamic arrays for adjacency lists or sparse matrix representations that can efficiently accommodate changes in the graph structure without significant overhead.

Yes, several specialized libraries and tools exist for graph representation and analysis, such as NetworkX in Python, igraph in R, and Neo4j for graph databases. These tools provide various functionalities for creating, analyzing, and visualizing graphs, making them invaluable resources for graph-related tasks.

Avatar photo

Top Free Courses

What is time complexity

What is Time Complexity And Why Is It Essential?

pattern program in python

Learn Pattern Program in Python – Examples and Code Explanation

lasso regression

A Complete understanding of LASSO Regression

21 open source python libraries

Top 30 Python Libraries To Know

python dictionary append

Python Dictionary Append: How To Add Key/Value Pair?

Free Data Science Courses

¿Qué es la Ciencia de Datos? – Una Guía Completa [2024]

Leave a comment cancel reply.

Your email address will not be published. Required fields are marked *

Save my name, email, and website in this browser for the next time I comment.

Great Learning Academy Free Online Courses

Table of contents

Learn Python practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn python interactively, dsa introduction.

  • What is an algorithm?
  • Data Structure and Types
  • Why learn DSA?
  • Asymptotic Notations
  • Master Theorem
  • Divide and Conquer Algorithm

Data Structures (I)

  • Types of Queue
  • Circular Queue
  • Priority Queue

Data Structures (II)

  • Linked List
  • Linked List Operations
  • Types of Linked List
  • Heap Data Structure
  • Fibonacci Heap
  • Decrease Key and Delete Node Operations on a Fibonacci Heap

Tree based DSA (I)

  • Tree Data Structure
  • Tree Traversal
  • Binary Tree
  • Full Binary Tree
  • Perfect Binary Tree
  • Complete Binary Tree
  • Balanced Binary Tree
  • Binary Search Tree

Tree based DSA (II)

  • Insertion in a B-tree
  • Deletion from a B-tree
  • Insertion on a B+ Tree
  • Deletion from a B+ Tree
  • Red-Black Tree
  • Red-Black Tree Insertion
  • Red-Black Tree Deletion

Graph based DSA

  • Graph Data Structure
  • Spanning Tree
  • Strongly Connected Components

Adjacency Matrix

Adjacency List

  • DFS Algorithm
  • Breadth-first Search
  • Bellman Ford's Algorithm

Sorting and Searching Algorithms

  • Bubble Sort
  • Selection Sort
  • Insertion Sort
  • Counting Sort
  • Bucket Sort
  • Linear Search
  • Binary Search

Greedy Algorithms

  • Greedy Algorithm
  • Ford-Fulkerson Algorithm
  • Dijkstra's Algorithm
  • Kruskal's Algorithm

Prim's Algorithm

  • Huffman Coding
  • Dynamic Programming
  • Floyd-Warshall Algorithm
  • Longest Common Sequence

Other Algorithms

  • Backtracking Algorithm
  • Rabin-Karp Algorithm

DSA Tutorials

Depth First Search (DFS)

Graph Data Stucture

A graph data structure is a collection of nodes that have data and are connected to other nodes.

Let's try to understand this through an example. On facebook, everything is a node. That includes User, Photo, Album, Event, Group, Page, Comment, Story, Video, Link, Note...anything that has data is a node.

Every relationship is an edge from one node to another. Whether you post a photo, join a group, like a page, etc., a new edge is created for that relationship.

graph data structure explained using facebook's example. Users, groups, pages, events, etc. are represented as nodes and their relationships - friend, joining a group, liking a page are represented as links between nodes

All of facebook is then a collection of these nodes and edges. This is because facebook uses a graph data structure to store its data.

More precisely, a graph is a data structure (V, E) that consists of

  • A collection of vertices V
  • A collection of edges E, represented as ordered pairs of vertices (u,v)

a graph contains vertices that are like points and edges that connect the points

In the graph,

  • Graph Terminology
  • Adjacency : A vertex is said to be adjacent to another vertex if there is an edge connecting them. Vertices 2 and 3 are not adjacent because there is no edge between them.
  • Path : A sequence of edges that allows you to go from vertex A to vertex B is called a path. 0-1, 1-2 and 0-2 are paths from vertex 0 to vertex 2.
  • Directed Graph : A graph in which an edge (u,v) doesn't necessarily mean that there is an edge (v, u) as well. The edges in such a graph are represented by arrows to show the direction of the edge.
  • Graph Representation

Graphs are commonly represented in two ways:

1. Adjacency Matrix

An adjacency matrix is a 2D array of V x V vertices. Each row and column represent a vertex.

If the value of any element a[i][j] is 1, it represents that there is an edge connecting vertex i and vertex j.

The adjacency matrix for the graph we created above is

graph adjacency matrix for sample graph shows that the value of matrix element is 1 for the row and column that have an edge and 0 for row and column that don't have an edge

Since it is an undirected graph, for edge (0,2), we also need to mark edge (2,0); making the adjacency matrix symmetric about the diagonal.

Edge lookup(checking if an edge exists between vertex A and vertex B) is extremely fast in adjacency matrix representation but we have to reserve space for every possible link between all vertices(V x V), so it requires more space.

2. Adjacency List

An adjacency list represents a graph as an array of linked lists.

The index of the array represents a vertex and each element in its linked list represents the other vertices that form an edge with the vertex.

The adjacency list for the graph we made in the first example is as follows:

adjacency list representation represents graph as array of linked lists where index represents the vertex and each element in linked list represents the edges connected to that vertex

An adjacency list is efficient in terms of storage because we only need to store the values for the edges. For a graph with millions of vertices, this can mean a lot of saved space.

  • Graph Operations

The most common graph operations are:

  • Check if the element is present in the graph
  • Graph Traversal
  • Add elements(vertex, edges) to graph
  • Finding the path from one vertex to another

Table of Contents

  • Introduction

Sorry about that.

Related Tutorials

DS & Algorithms

Graph Representation Learning Based on Specific Subgraphs for Biomedical Interaction Prediction

Ieee account.

  • Change Username/Password
  • Update Address

Purchase Details

  • Payment Options
  • Order History
  • View Purchased Documents

Profile Information

  • Communications Preferences
  • Profession and Education
  • Technical Interests
  • US & Canada: +1 800 678 4333
  • Worldwide: +1 732 981 0060
  • Contact & Support
  • About IEEE Xplore
  • Accessibility
  • Terms of Use
  • Nondiscrimination Policy
  • Privacy & Opting Out of Cookies

A not-for-profit organization, IEEE is the world's largest technical professional organization dedicated to advancing technology for the benefit of humanity. © Copyright 2024 IEEE - All rights reserved. Use of this web site signifies your agreement to the terms and conditions.

IMAGES

  1. Statistics: Ch 2 Graphical Representation of Data (1 of 62) Types of Graphs

    types of graph representation

  2. Types Of Graph Representation In Data Structure

    types of graph representation

  3. Types Of Graph Representation In Data Structure

    types of graph representation

  4. Best Types of Charts and Graphs for Data Visualization

    types of graph representation

  5. Types Of Graph Representation In Data Structure

    types of graph representation

  6. How To Draw Graphs?|Graphical Representation of Data|Statistical Graphs

    types of graph representation

VIDEO

  1. Graph Representation in Data Structure

  2. Representation of Graph

  3. graph representation part-1| Adjacency matrix

  4. Diagrammatic and Graphical Representation

  5. Basics of Graph Representation and its Types by Dr. M Lakshmi Prasad

  6. Types Of Graph Theory Part 2

COMMENTS

  1. Graph and its representations

    A Graph is a non-linear data structure consisting of vertices and edges. The vertices are sometimes also referred to as nodes and the edges are lines or arcs that connect any two nodes in the graph. More formally a Graph is composed of a set of vertices ( V ) and a set of edges ( E ). The graph is denoted by G (V, E).

  2. Graphs

    The following are the most common types of graphs: Undirected graph: An undirected graph is one in which its edges have no orientations, i.e. no direction is associated with any edge. The edges \((x,y)\) and \((y,x)\) are equivalent. ... An adjacency list representation of a graph is a way of associating each vertex (or node) in the graph with ...

  3. Representing graphs (article)

    The adjacency list representation for an undirected graph is just an adjacency list for a directed graph, where every undirected edge connecting A to B is represented as two directed edges: -one from A->B -one from B->A e.g. if you have a graph with undirected edges connecting 0 to 1 and 1 to 2 your adjacency list would be: [ [1] //edge 0->1

  4. Describing graphs (article)

    Describing graphs. Here's one way to represent a social network: A line between the names of two people means that they know each other. If there's no line between two names, then the people do not know each other. The relationship "know each other" goes both ways; for example, because Audrey knows Gayle, that means Gayle knows Audrey.

  5. See 20 Different Types Of Graphs And Charts With Examples

    A graph or chart is a graphical representation of qualitative or quantitative data. It uses different symbols such as bars, lines, columns, tables, box plots, maps, and more, to give meaning to the information, making it easier to understand than raw data. ... As we saw with different graph types previously, the bullet chart can be vertical ...

  6. PDF Chapter 9 Graphs: Definition, Applications, Representation

    vin G. An undirected graph is connected if all vertices are reachable from all other vertices. A directed graph is strongly connected if all vertices are reachable from all other vertices. Cycles. In a directed graph a cycle is a path that starts and ends at the same vertex. A cycle can have length one (i.e. a self loop).

  7. Graph theory

    Graphs can be used to model many types of relations and processes in physical, biological, social and information systems. Many practical problems can be represented by graphs. ... Representation. A graph is an abstraction of relationships that emerge in nature; hence, it cannot be coupled to a certain representation. The way it is represented ...

  8. Introduction to Graphs

    Add and Remove Edge in Adjacency List representation of a Graph; Add and Remove Edge in Adjacency Matrix representation of a Graph; Searching on Graphs - Search an entity in the graph. Traversal of Graphs - Traversing all the nodes in the graph. Difference between Tree and Graph: Trees are the restricted types of graphs, just with some more ...

  9. Graphs in Python

    Graphs in Python can be represented in several different ways. The most notable ones are adjacency matrices, adjacency lists, and lists of edges. In this guide, we'll cover all of them. When implementing graphs, you can switch between these types of representations at your leisure. First of all, we'll quickly recap graph theory, then explain ...

  10. 10.1. Chapter Introduction: Graphs

    Here is a small sampling of the types of problems that graphs are routinely used for. ... Which graph representation is more space efficient depends on the number of edges in the graph. The adjacency list stores information only for those edges that actually appear in the graph, while the adjacency matrix requires space for each potential edge ...

  11. Graph Representation Tutorials & Notes

    Types of graphs. Undirected: An undirected graph is a graph in which all the edges are bi-directional i.e. the edges do not point in any specific direction. Directed: A directed graph is a graph in which all the edges are uni-directional i.e. the edges point in a single direction. Weighted: In a weighted graph, each edge is assigned a weight or ...

  12. Graph Representation

    A graph is a data structure that consist a sets of vertices (called nodes) and edges. There are two ways to store Graphs into the computer's memory: Sequential representation (or, Adjacency matrix representation) Linked list representation (or, Adjacency list representation) In sequential representation, an adjacency matrix is used to store the ...

  13. 8.4: Graph Representations

    Adjacency Matrix Representation. An adjacency matrix is one of the two common ways to represent a graph. The adjacency matrix shows which nodes are adjacent to one another. Two nodes are adjacent if there is an edge connecting them. In the case of a directed graph, if node \(j\) is adjacent to node \(i\), there is an edge from \(i\) to \(j\).

  14. Graphical Representation

    Frequency Distribution Graphs - Example: Frequency Polygon Graph; Principles of Graphical Representation. Algebraic principles are applied to all types of graphical representation of data. In graphs, it is represented using two lines called coordinate axes. The horizontal axis is denoted as the x-axis and the vertical axis is denoted as the y ...

  15. What is Graph in Data Structure & Types of Graph?

    A graph is a type of non-linear data structure made up of vertices and edges. Vertices are also known as nodes, while edges are lines or arcs that link any two nodes in the network. In more technical terms, a graph comprises vertices (V) and edges (E). The graph is represented as G (E, V). 7.

  16. Types of Graphs and Charts And Their Uses

    Every type of graph is a visual representation of data on diagram plots (ex. bar, pie, line chart) that show different types of graph trends and relationships between variables. Although it is hard to tell what are all the types of graphs, this page consists all of the common types of statistical graphs and charts (and their meanings) widely ...

  17. Introduction to Graphs

    Bar graph. Line graph. Histogram. Pie chart. Stem and leaf plot. Pictograph. Scatter diagrams. The graph is nothing but an organized representation of data. Learn about the different types of data and how to represent them in graphs with different methods.

  18. Graphs in Data Structures

    Graph representation is a way of structuring and visualizing data using nodes (vertices) and edges. It is a technique to store graphs in the memory of a computer. In a graph, nodes represent individual entities, while edges represent the relationships or connections between those entities.

  19. Types of Graphs with Examples

    Dense Graph s: A graph with many edges compared to the number of vertices. Example: A social network graph where each vertex represents a person and each edge represents a friendship. Types of Graphs: 1. Finite Graphs A graph is said to be finite if it has a finite number of vertices and a finite number of edges.

  20. Representing Graphs in Data Structures

    In this blog post, we will explore the representation of graphs in data structures and explain the various representations of graphs with detailed examples that will help you understand the concept. ... Directed Graph- Also known as a digraph, a directed graph is a type of graph in which edges have a direction. This means that the relationship ...

  21. Graph Data Structure

    Graph Terminology. Adjacency: A vertex is said to be adjacent to another vertex if there is an edge connecting them.Vertices 2 and 3 are not adjacent because there is no edge between them. Path: A sequence of edges that allows you to go from vertex A to vertex B is called a path. 0-1, 1-2 and 0-2 are paths from vertex 0 to vertex 2.; Directed Graph: A graph in which an edge (u,v) doesn't ...

  22. 44 Types of Graphs & Charts [& How to Choose the Best One]

    Market segments are often divided based on age and gender, and a population pyramid is an ideal visual representation of the two groups. The graph classically takes on the shape of a pyramid when a population is healthy and growing -- the largest groups are the youngest, and each gender dwindles somewhat equally as the population ages, leaving the smallest groups at the top of the graph.

  23. Graph (abstract data type)

    A directed graph with three vertices (blue circles) and three edges (black arrows).. In computer science, a graph is an abstract data type that is meant to implement the undirected graph and directed graph concepts from the field of graph theory within mathematics.. A graph data structure consists of a finite (and possibly mutable) set of vertices (also called nodes or points), together with a ...

  24. Graph Representation Learning Based on Specific Subgraphs for

    Graph representation learning (GRL) has incredible potential to efficiently predict the interactions from biomedical networks by modeling the robust representation for each node. However, the current GRL-based methods learn the representation of nodes by aggregating the features of their neighbors with equal weights. Furthermore, they also fail ...

  25. Learning-Based Link Anomaly Detection in Continuous-Time Dynamic Graphs

    Anomaly detection in continuous-time dynamic graphs is an emerging field yet under-explored in the context of learning-based approaches. In this paper, we pioneer structured analyses of link-level anomalies and graph representation learning for identifying anomalous links in these graphs. First, we introduce a fine-grain taxonomy for edge-level anomalies leveraging structural, temporal, and ...