Data visualization: Basic plots in Matplotlib

 In python, there are two popularly known data visualization libraries namely matplotlib and seaborn.

In this post we will concentrate on data visualisation using matplotlib.

Using matplotlib we can create static, interactive and even animated visualizations in python. It is easy to use and provide 

To install matplotlib:

conda install matplotlib    ## For Ancaonda users

pip install matplotlib     ## For python users

After installing matplotlib we need to import matplotlib library in console to use it.

>> import matplotlib.pyplot as plt

To display the plots in the editor we need to use the below command.

>> plt.show() 

But in jupyter notebook, we need a seperate command which is given below to display the plots.

>> %matplotlib inline

Lets start with basic plot

>> x= np.linspace(0,25,11)
>> y=x**2
>> print('x:', x)
>> print('y:', y)

Output:
x: [ 0.   2.5  5.   7.5 10.  12.5 15.  17.5 20.  22.5 25. ]
y: [  0.     6.25  25.    56.25 100.   156.25 225.   306.25 400.   506.25
 625.  ]

Here we considered values 11 values lies between 0 and 25 as x values. Square of these 'x' values were considered as 'y' values. 

Now lets plot x vs y

>> plt.plot(x, y)



This is the basic plot of x and y. Here the x-axis indicates the 'x' values and y axis indicates the 'y' values.  Here the default color of the plot is in blue color.

Lets give the title, x and y labels to the plot.

>> plt.plot(x,y)
>> plt.title('Plot of x and y values')
>> plt.xlabel('x  values')
>> plt.ylabel('y values')
>> plt.show( )

Output:


We can also change the color and the design of the plot as follows

>> plt.plot(x,y, 'mo-')
>> plt.title('Plot of x and y values')
>> plt.xlabel('x  values')
>> plt.ylabel('y values')
>> plt.show()

Output:



Here we plotted the graph in magenta with combination of circles and dashes ('o-').

All the available colors with different matplot line styles and markers can be found here

https://matplotlib.org/2.1.2/api/_as_gen/matplotlib.pyplot.plot.html

There are different plots such as scatter plot, barplot and histograms

Scatterplot:

Scatterplot requires 2 variables similar to line plot.

>> plt.scatter(x,y)
>> plt.title('Scatter plot of x and y values')
>> plt.xlabel('x  values')
>> plt.ylabel('y values')
>> plt.show()


Output:


 Bar plot:

Barplot also requires 2 variables to plot a graph. Bar graphs are used to display different categorical organised data. X axis indiates the different categories in the  data and Y axis indicates the frequency of occurance of the data in each category.

>> plt.bar(x,y)
>> plt.title('Bar plot of x and y values')
>> plt.xlabel('x  values')
>> plt.ylabel('y values')
>> plt.show()

Output:
Histogram:
 Histogram can be plotted for a single variable.
Histogram basically shows the distribution of the data. It displays the data which are in continous intervals.


plt.boxplot(data,vert=True,patch_artist=True);  

Comments