How to create graphs in python

Python — Graphs

A graph is a pictorial representation of a set of objects where some pairs of objects are connected by links. The interconnected objects are represented by points termed as vertices, and the links that connect the vertices are called edges. The various terms and functionalities associated with a graph is described in great detail in our tutorial here.

In this chapter we are going to see how to create a graph and add various data elements to it using a python program. Following are the basic operations we perform on graphs.

  • Display graph vertices
  • Display graph edges
  • Add a vertex
  • Add an edge
  • Creating a graph

A graph can be easily presented using the python dictionary data types. We represent the vertices as the keys of the dictionary and the connection between the vertices also called edges as the values in the dictionary.

Take a look at the following graph −

Array Declaration

Example

We can present this graph in a python program as below −

# Create the dictionary with graph elements graph = < "a" : ["b","c"], "b" : ["a", "d"], "c" : ["a", "d"], "d" : ["e"], "e" : ["d"] ># Print the graph print(graph)

Output

When the above code is executed, it produces the following result −

Display graph vertices

To display the graph vertices we simple find the keys of the graph dictionary. We use the keys() method.

class graph: def __init__(self,gdict=None): if gdict is None: gdict = [] self.gdict = gdict # Get the keys of the dictionary def getVertices(self): return list(self.gdict.keys()) # Create the dictionary with graph elements graph_elements = < "a" : ["b","c"], "b" : ["a", "d"], "c" : ["a", "d"], "d" : ["e"], "e" : ["d"] >g = graph(graph_elements) print(g.getVertices())

Output

When the above code is executed, it produces the following result −

Display graph edges

Finding the graph edges is little tricker than the vertices as we have to find each of the pairs of vertices which have an edge in between them. So we create an empty list of edges then iterate through the edge values associated with each of the vertices. A list is formed containing the distinct group of edges found from the vertices.

class graph: def __init__(self,gdict=None): if gdict is None: gdict = <> self.gdict = gdict def edges(self): return self.findedges() # Find the distinct list of edges def findedges(self): edgename = [] for vrtx in self.gdict: for nxtvrtx in self.gdict[vrtx]: if not in edgename: edgename.append() return edgename # Create the dictionary with graph elements graph_elements = < "a" : ["b","c"], "b" : ["a", "d"], "c" : ["a", "d"], "d" : ["e"], "e" : ["d"] >g = graph(graph_elements) print(g.edges())

Output

When the above code is executed, it produces the following result −

Adding a vertex

Adding a vertex is straight forward where we add another additional key to the graph dictionary.

Example

class graph: def __init__(self,gdict=None): if gdict is None: gdict = <> self.gdict = gdict def getVertices(self): return list(self.gdict.keys()) # Add the vertex as a key def addVertex(self, vrtx): if vrtx not in self.gdict: self.gdict[vrtx] = [] # Create the dictionary with graph elements graph_elements = < "a" : ["b","c"], "b" : ["a", "d"], "c" : ["a", "d"], "d" : ["e"], "e" : ["d"] >g = graph(graph_elements) g.addVertex("f") print(g.getVertices())

Output

When the above code is executed, it produces the following result −

Adding an edge

Adding an edge to an existing graph involves treating the new vertex as a tuple and validating if the edge is already present. If not then the edge is added.

class graph: def __init__(self,gdict=None): if gdict is None: gdict = <> self.gdict = gdict def edges(self): return self.findedges() # Add the new edge def AddEdge(self, edge): edge = set(edge) (vrtx1, vrtx2) = tuple(edge) if vrtx1 in self.gdict: self.gdict[vrtx1].append(vrtx2) else: self.gdict[vrtx1] = [vrtx2] # List the edge names def findedges(self): edgename = [] for vrtx in self.gdict: for nxtvrtx in self.gdict[vrtx]: if not in edgename: edgename.append() return edgename # Create the dictionary with graph elements graph_elements = < "a" : ["b","c"], "b" : ["a", "d"], "c" : ["a", "d"], "d" : ["e"], "e" : ["d"] >g = graph(graph_elements) g.AddEdge() g.AddEdge() print(g.edges())

Output

When the above code is executed, it produces the following result −

Источник

How to Create Vivid graphs using Python Language

plotting graphs in python

image

Plotting graphs in python can be a tricky affair, but a few simple steps can help you generate a graph easily. To generate graphs in Python you will need a library called Matplotlib. It helps in visualizing your data and makes it easier for you to see the relationship between different variables. Before starting with the graph, it is important to first understand Matplotlib and its functions in Python.

Why is data Visualization needed?

Visualization of data is a practice of presenting the data in a simple manner (in graphical or pictorial format), through which even a non-technical person can understand it easily as the human brain can process information easily when it is in pictorial or graphical form.

It allows us to quickly interpret data and adjust different variables to observe their effects. You can simply interpret the information from data visualization which is very helpful for a person (a Non-technical person) to understand.

Introduction to Matplotlib

Matplotlib is a library used in Python to generate graphs and lines for 2D graphics. Matplotlib package is totally written in Python. Matplotlib uses simple commands to generate simple plots for your data.

Installation

The first step is to install the Matplotlib using the pip command given below.

Using pip command it will take care of dependencies while installing the library in Python.

Matplotlib Python Plot

You might be thinking, to start with the plotting graphs in python there would be some typical commands which you will be using to generate graphs. Matplotlib has tremendously reduced that effort which provides a flexible library and much built-in defaults to simply generate graphs. You need to make sure that you make the necessary imports, prepare data and start with the plot() function.

Use this import to get started with your Matplotlib plot:

>>> import matplotlib.pyplot as plt

To generate data later also NumPy import will be used. To import NumPy use this syntax:

plotting graphs in python

Also, use show() function to show the resulting graph. Let us see a simple example of how we can start generating a graph.

  • # Make sure to import the necessary packages and modules
  • import pyplot as plt
  • import numpy as np
  • # Prepare your data
  • z = np.linspace(0, 10, 100)
  • # Plotting the data
  • plot(z, z, label=’linear’)
  • # Adding a legend
  • legend()
  • # Result
  • plt.show()

Run your code and see the resulting plot. Result:

You can also look for another example to generate a most simple graph using Matplotlib.

Simple graph

  • from Matplotlib import pyplot as plt
  • # Plotting of graph
  • plot([1,2,3],[4,5,1])
  • # Showing the result
  • plt.show()

plotting graphs in python

In the above example, we’ve just plotted a simple graph without any title, x-axis or y-axis. Moving forward we will be learning how to add title and labels to the graph.

Adding label and titles to your graph

  • from matplotlib import pyplot as plt
  • x=[5,8,10]
  • y=[12,16,6]
  • plot(x,y)
  • title(‘info’)
  • ylabel(‘Y axis’)
  • xlabel(‘X axis’)
  • show()

plotting graphs in python

In the above example, we’ve shown the x-axis and y-axis by a simple command plt.ylabel() and title by plt.title(). We have used plot(x,y) instead of using direct numbers for plotting the X and Y axis.

This graph doesn’t include any style or color. What if you want to add some style or change the width of the line or add color to the graph? We’ll see a simple code to generate a graph with different styles and colors.

Adding style to the graph

plotting graphs in python

  • from matplotlib import pyplot as plt
  • from matplotlib import style
  • use(‘ggplot’)
  • x=[5,8,10]
  • y=[12,16,6]
  • x1=[6,9,11]
  • y1=[6,15,7]
  • plot(x,y,’g’,label=’line one’,linewidth=5)
  • plot(x1,y1,’c’,label=’line two’,linewidth=5)
  • title(‘Epic info’)
  • ylabel(‘Y axis’)
  • xlabel(‘X axis’)
  • show()

Result:

To introduce color in different lines we have used ‘g’ for green and ‘c’ for cyan. We can also introduce the thickness of the line by using linewidth function. As we have only used default grid lines, to change the color of the grid line use this simple command before plt.show()

If you want to add a highlight to the graph which shows the details of the line you can use legend() function by using this simple command.

After adding legend() and grid() function code will look like this.

  • from matplotlib import pyplot as plt
  • from matplotlib import style
  • use(‘ggplot’)
  • x=[5,8,10]
  • y=[12,16,6]
  • x1=[6,9,11]
  • y1=[6,15,7]
  • plot(x,y,’g’,label=’line one’,linewidth=5)
  • plot(x1,y1,’c’,label=’line two’,linewidth=5)
  • title(‘Epic info’)
  • ylabel(‘Y axis’)
  • xlabel(‘X axis’)
  • grid(True,color=’K’)
  • legend()
  • show()

In the above examples we have learned how to change width line, style, and grid or add a highlighter and now we’ll see how we can plot different types of graphs using Matplotlib in Python

Types of plots

There are several types of the plot which we will generate in this section using Matplotlib.

Bar graphs are used generally to compare different groups using visualizations. Whether it be a change of market or change in revenue, using a bar graph we can easily determine and compare the actual results.

plotting graphs in python

Code to generate Bar graph in Python:

  • Import pyplot as plt
  • bar([1,3,5,7,9],[5,2,7,8,2], label=“Example one”)
  • bar([2,4,6,8,10],[8,6,2,5,6], label=“Example two”,color=‘g’)
  • legend()
  • xlabel(‘bar number’)
  • ylabel(‘bar height’)
  • title(‘Bar Graph’)
  • show()

Result:

Histogram: Histogram graph is generally used to display the statistical information or the distribution of successive process data set. The histogram is generally used for continuous data. Histogram or Bar graph may seem similar but a general difference between histogram plot and bar graph plot is that a histogram plot is used to display the distribution of variables while bar graph is used to display the comparison between variables.

Code to generate the Histogram graph in Python:

  • import matplotlib pyplot as plt
  • population_ages=[22,55,62,45,21,22,34,42,42,4,99,102,110,120,121,122,130,111,115,112,80,75,65,54,44,43,42,48]
  • bins = [0,10,20,30,40,50,60,70,80,90,100,110,120,130]
  • hist(population_ages, bins, histtype=’bar’,r width=0.8)
  • xlabel(‘x’)
  • ylabel(‘y’)
  • title(‘Histogram’)
  • legend()
  • show()

Result:plotting graphs in python

  1. Scatter Plot: Using a scatter plot you can compare two variables and can determine the correlation between them. The values of the variables are represented in the form of a dot. Example of a scatter plot is shown in the image.

Code to generate Scatter plot:

  • import pyplot as plt
  • x=[1,2,3,4,5,6,7,8]
  • y=[5,2,4,2,1,4,5,2]
  • scatter(x,y, label=’skitscat’, color=’k’, s=25, marker=“o”)
  • xlabel(‘x’)
  • ylabel(‘y’)
  • title(‘Scatter Plot’)
  • legend()
  • show()

Result:plotting graphs in pythonStack Plot: Stack plot or area plot is similar to the line graphs. They can be used to track changes of one or more variables. Stack plot is good to use when you are tracking changes in two or more related group that make up a whole category. Example of stack plots: plotting graphs in pythonCode to generate Stack Plot

  • importpyplot as plt
  • days = [1,2,3,4,5]
  • sleeping =[7,8,6,11,7]
  • eating = [2,3,4,3,2]
  • working =[7,8,7,2,2]
  • playing = [8,5,7,8,13]
  • plot([],[],color=’m’, label=’Sleeping’, linewidth=5)
  • plot([],[],color=’c’, label=’Eating’, linewidth=5)
  • plot([],[],color=’r’, label=’Working’, linewidth=5)
  • plot([],[],color=’k’, label=’Playing’, linewidth=5)
  • stackplot(days, sleeping,eating,working,playing, colors=[‘m’,’c’,’r’,’k’])
  • xlabel(‘x’)
  • ylabel(‘y’)
  • title(‘Interesting Graph\n Check it out’)
  • legend()
  • show()

Result:Pie Chart: Pie chart is used to display the statistical data in the form of a circular Different variables are represented in the form of ‘pie slices’. Pie chart generally shows the percentage of different categories by dividing the circle into proportional pie slices. A pie chart can be useful to show the exact quantity which has been consumed by the category with representation. It is also useful when comparing more than two variables using a graph. Code to generate Pie chart:

  • Import pyplot as plt
  • x=[7,2,2,13]
  • activities=[‘sleeping’,’eating’,’working’,’playing’]
  • cols=[‘c’,’m’,’r’,’b’]
  • pie(x,
  • labels=activites,
  • colors=cols,
  • startangle=90,
  • shadw=True,
  • explode=(0,0.1,0,0),
  • autopct=’%1.1f%%’)
  • title(‘Pie Plot’)
  • show()

Result:Working with Multiple Plots

As we have discussed various types of plots in the above section, we are going to see how we can work with multiple graphs.

plotting graphs in python

Code:

  • import numpy as np
  • import pyplot as plt
  • def f(t):
  • returnexp(-t) * np.cos(2*np.pi*t)
  • t1 = np.arange(0.0, 5.0, 0.1)
  • t2 = np.arange(0.0, 5.0, 0.02)
  • subplot(221)
  • plot(t1, f(t1), ‘bo’, t2, f(t2))
  • subplot(222)
  • plot(t2, np.cos(2*np.pi*t2))
  • show()

Result:

Now, you have learned how plotting graphs in python used to be done and what are the various types of plots which you can generate using Matplotlib in Python.

Источник

Читайте также:  Php write uploaded file
Оцените статью