How to create Scatter Plot using Matplotlib Library
Scatter plot is one of the
commonly used plots which is also thought as cousin of line plot in data
visualization or data science. In this tutorial post we will discuss about
scatter plot about how to create it using Matplotlib library and customize
different properties of this plot based on our needs in data visualization.
In scatter plots, we represent
points individually with circle, dot or any other shape instead of joining
points by line segment as we mostly do in line plotting.
Let’s demonstrate some examples about how to create scatter plots. For generating scatter plots, we must start with following code to use Matplotlib library by importing it in our Jupiter notebook.
In[1]: import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
After importing matplotlib.pyplot
module and numpy library in notebook, you can now easily use functions provided
from these libraries as shown below;
In[2]: x=np.linspace(0, 10, 40) # Define x ndarray with total 20 elements b/w 0 & 10
y=np.cos(x) # Define y as cosine function of x
plt.scatter(x, y) # Generate a scatter plot
From the above plot we will notice that function y=cos(x) in y-axis is plotted against x in x-axis. But the above plot is so
simple, you can customize properties of this plot as shown below;
In[3]: plt.style.use('seaborn-whitegrid') # Set Style of plot
plt.scatter(x,y, c='green', marker='d', alpha=0.5) # Create scatter plot
plt.ylim(-1.5,1.5) # Set limits of y-axis of plot
plt.xlabel('x') # Set label of x-axis of plot
plt.ylabel('cos(x)') # Set label of y-axis of plot
plt.title('Plotting cos(x) versus x') # Set title of our plot
From the above lines of code In[3]
you can find following points;
- we have first set style of plot from default style to ‘seaborn-whitegrid’ which is one of a list of styles provided by Matplotlib library. To list all available styles you may use command line print(plt.style.available) in IPython shell or Jupyter Notebook.
- In the next line we used scatter function to plot y against x and also we added arguments c=’green’, marker=’d’ and alpha=0.5 to this functions to customize color of point, style of point markers and blending color of point respectively.
- Using plt.ylim() function, we set maximum limits of y-axis of plot to be displayed with first argument as minimum limit and second argument as maximum limit of y-axis.
- We also set labels of x-axis and y-axis of plot using function plt.xlabel( ) and plt.ylabel( ) respectively.
- And in the final line of code we have given title of plot using function plt.title( ) with title name as string argument enclosed in it.
Comments
Post a Comment