Lets learn How to use the MatPlot library using Python language from this article. This is the first article of our How to series if you like it please leave the comment or ask questions so we can bring more How to articles on various topics.
Introduction to Matplotlib
Matplotlib is a library that provides an API to plot graphs and visualization abilities.You can create stable, animated and concerted visualization because it is a complete library in python. You can create layouts and graph visual styles on your own. Matplotlib is an open-source plotting library that supports various graphs. It is frequently used in web application servers, python scripts. This makes your simple concept as simple and hard as possible. This library is mostly used for data visualization
Installation
You can install the Matplot library by using python packages like pip or conda on any operating system like windows, linux, macOS.
Steps to install Matplotlib in windows:
- Based on your operating system, download the python from python.org and install it.
- If python is already installed skip the first step.
- To get installed the version of python and pip on your system , type the below given commands in the command prompt:
>python --version (Python installed version is displayed).
>pip -V (PIP installed version is displayed).
• Then install Matplotlib using the following PIP command in Command prompt terminal:
>pip install matplotlib
- To check whether matplotlib is successfully installed, execute following commands to get the version of matplotlib installed will be displayed.
>import matplotlib
>matplotlib __version__
Steps to install Matplotlib in MacOS:
- By using given below commands to check whether pip3 and python3 are installed or not.
>python3 - -version
>pip3 - -version
- By using given below commands to check whether pip3 and python3 are installed or not.
>pip3 install matplotlib
How to create Simple Graphs using Matplot Library
Pyplot:
Matplotlib.pyplot is a state- based interface to matplotlib. Matplotlib is designed like MATLAB. Pyplot is used to create the figure. The biggest advantage of using this is that it is free and open- source.
The several plot you can design using pyplot are Line plot, Histogram, Pie charts, scatters etc.,
In the plot function,parameters that accept to use axes values and graph format. You can show 2D array data as an image.
Step 1:
Importing the matplot library
import matplotlib.pyplot as graph
Step 2:
Composing the x and y data for plotting the line from (1,1) to (5,5).
X = [1,2,3,4,5]
Y = [1,2,3,4,5]
Step 3:
Pyplot package is assigned as a graph here. Plot function is to plot x and y positions.
graph.plot(X, Y)
When you give only Y axis coordinates ,automatically x axis coordinates start with 0 and length of the x axis values[0 .. length(Y)-1]. Plot() can be called with one axis (Y).
graph.plot(Y)
Step 4:
Show method is used to show the graph as output.
graph.show()
Output:
Graph using Markers
Markers will plot the (x,y) points highlighted in the graph. You have many types and styles of markers to plot in matplotlib. Marker styles and shapes can be customized by passing the parameter..
Markers must be passed as additional arguments to the plot method.
The following table represents possible markers used in matplotlib:
Markers | Representation |
. | Dot |
o | Circle |
* | Star |
^ | Triangle |
| | Line |
x | Cross |
graph.plot(X, Y, marker = 'o')
Output:
Line Styles
Similar to marker customization, the line of the graph also can be customized with styles such as solid line, dotted line, dashed line etc.
Line style shares the same parameter with the marker, where the first character represents the marker and second optional character represents the line style.
For example,
“o-” represents circle marker with solid line
“*–” represents star marker with dashed line
Character | Representation |
– | Solid Line |
– | Dashed Line |
: | Dotted Line |
-. | Dashed/Dotted Line |
You can also leave it empty to plot only markers.
graph.plot(X, Y, 'o:')
Output:
Line Colors
You can customize colors through the same parameter. The parameter will looks like something given below,
“<marker-character><line-style><color-code>”
The second and third characters are not necessary because it is optional.
Color Code | Color |
r | Red |
g | Green |
b | Blue |
w | White |
k | Black |
graph.plot(X, Y, 'o-.g')
Output:
Marker Border Colors
Unlike line color, marker border color needs an additional parameter to be passed. The marker color will be decided by the line color itself but the marker edge color alone can be customized separately.
graph.plot(X, Y, "o-.g", mec = 'r'
The parameter name is markeredgecolor / mec which accepts the same color code characters as the line color codes.
Output:
Marker Size
The marker size can be adjusted with the parameter markersize / ms. The default size of the marker will be 72 points per inch.
graph.plot(X, Y, "o-.g", mec = 'r')
Output:
Labels for Plot
- To show the label for x and y-axis, you can use xlabel() and ylabel() functions.
- To show the title of the graph, you can use title() function.
import matplotlib.pyplot as graph
X = [1,2,3,4,5]
Y = [4,2,1,7,9]
graph.plot(X, Y)
graph.title("Sample plot")
graph.xlabel("X Label")
graph.ylabel("Y Label")
graph.show()
Output:
Grids
Matplot library allows us to draw grid lines over the graph which will be helpful during analysis of the data.
The API that enables grid is grid().
import matplotlib.pyplot as graph
X = [1,2,3,4,5]
Y = [1,2,3,4,5]
graph.plot(X, Y, "*:b", mec = 'r', ms = 20)
graph.grid()
graph.show()
Output:
We can also mention which exact axis data the grid lines need to be aligned.
graph.grid(axis = 'y')
Output:
The grid lines also can be customizable with line color, line style, etc.
graph.grid(color = 'g', linestyle = ':', linewidth = 1.8)
Output:
Scatter
Scatter is used to plot on dot for each combination. Scatter() function is used to plot the scatter.
It requires two arrays with same length, one is used for x axis values and another used for y axis values.
Output:
Bar Plots
The bar graph is the pictorial representation of data. bar() function is used to draw bar representation.
import matplotlib.pyplot as graph
X = [3,7,12,19,5,11,9,4,13,20]
Y = [25,33,46,31,28,44,60,37,56,68]
graph.scatter(X, Y)
graph.show()
Output:
Pie charts
Pie chart is the circular representation of data. pie() function is used to draw the pie charts. You can add label parameter to show each data representation and different color is used for each data randomly.
import matplotlib.pyplot as graph
X = [25,30,60,45,70]
Y = ["C","C++","C#","Python","Java"]
graph.pie(X, labels = Y)
graph.show()
Output
Fun Activity
graph.grid(axis = 'y')
Let’s do a fun activity. Our goal of the activity is to have some fun along with practicing the topics we covered so far. The activity involves a series of steps. Output will based on random generation of color, style, marker related things. Output may be attractive or simple , it based on random generating values. This will be very interesting. Let’s start,
Step 1:
During the activity, we are going to use the following snippet more than one time, which will choose a random entry from a list.
listOfItems = [‘A’, ‘B’, ‘C’, ‘D’]
random.choice(listOfItems)
Step 2:
Import the matplot library. You have to import the random library as we discussed in step 1 to use random shuffling.
import matplotlib.pyplot as graph
Step 3:
Prepare a list of possible customizations factors of a graph such as line color, line style, markers, etc.
colors = ['r', 'g', 'b', 'w', 'k']
markers = ['*', '^', 'o']
lineStyles = ['-', ':', '--', '-.']
Step 4:
Preparing the random data. X and Y created with empty array. Then randomly x value is append one number from 0 to 50. Y value append from 0 to x value. Randint function takes parameters as lower value and upper value , gives random value from lower to upper value.
X = []
Y = []
for x in range(50):
X.append(x)
Y.append(random.randint(0, x))
Step 5:
Creating empty marker argument.Passing argument as marker, linestyles, colors to Get random value from that choice
marker_arg = ''
marker_arg = marker_arg + random.choice(markers)
marker_arg = marker_arg + random.choice(lineStyles)
marker_arg = marker_arg + random.choice(colors)
Step 6:
Randomly selecting the edge color from colors. Marker size will be from 1 to 5 any number.
marker_edge_color = random.choice(colors)
marker_size = random.randint(1, 5)
Step 7:
In this step, Grid related stuffs added. Grid linestyle is from line style. Grid line width from 1 to 5 random numbers. Grid color is random choice from colors..
grid_line_style = random.choice(lineStyles)
grid_line_width = random.randint(1, 5)
grid_color = random.choice(colors)
Step 8:
Plot method is to plotting the x, y values with marker type, marker edge color, marker size. Grid method is to update color of the grid, style, width of the grid line..
graph.plot(X, Y, marker_arg, mec = marker_edge_color, ms = marker_size)
graph.grid(color = grid_color, linestyle = line_style, linewidth = line_width)
Step 9:
Show method is used to show output generated by using random markers related, grid related.
graph.show()
The fun behind this activity is the output will be different whenever you re-run the program. It may look very attractive based on the combination of the colors.
Sample Output 1:
Sample Output 2: