###### Blog Category(283 Blogs)

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.

*pip install matplotlib*

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:

>>> import numpy as np

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()

**Result:**

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()

**Result:**

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**

- 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()*

**Result:**

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.

**Result:**

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 Graph
- Histograms
- Scatter Plot
- Stack Plot
- Pie Plot

**Bar graph: **

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.

**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()

- 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:**

**Stack 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:

**Code 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.

**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.