Data Visualization using Python's Matplotlib Library

in #utopian-io7 years ago (edited)

800px-Matplotlib_logo.svg.png

Matplotlib is an open source Python plotting library. It is written by John D.Hunter and has an active development community.
Matplotlib produces publication quality figures in Python scripts, IPython shell, Jupyter notebook, web applications and several gui toolkits. Using this we can generate variety of charts like plots, histograms, barcharts, scatter plots, error plots etc.
One of the most popular used case of Matplotlib is for data analysis and visulation.

In this tutorial, I'll show how we can use Matplotlib for creating line charts, bar charts, pie charts and donut charts.

What this tutorial covers ?

Difficulty

  • Basic

Installation

Matplotlib requires pyparsing, cycler, numpy and pytz libraries for installation. Matplotlib and all of its dependencies can be installed using pip.

pip install matplotlib

Verify if it is properly installed by importing matplotlib.

import matplotlib

install.gif

Creating a Line Charts

The below three line of code generates a simple line chart.

example1_code.PNG

  • In the above code we import matplotlib.pyplot module as plt for plotting the chart.

import matplotlib.pyplot as plt

The plt.plot(X, Y) plots the data to a canvas in the computer's memory.

In the above example:
X = [10, 20, 30]
Y = [2, 4, 6]

plt.plot([10, 20, 30], [2, 4, 6])

  • The plt.plot(X, Y) plots the data and stores it in computer's memory. However, it is not yet displayed. The plt.show() displays this plot on the screen.

plt.show()

Output

example1.png

The chart window has several options :

  • To zoom on certain area of the chart click on magnifing.PNG icon and select the area to zoom. The X and Y values are displayed at the bottom-right corner.

  • To changes several aspects of chart like left, right, top and bottom padding, click on filter.PNG icon and use the slider to change the values.

  • To save the chart, click on save.PNG icon and select the location to save the file.

filer_example1.gif

Adding Chart Title and labels

  • To add a title to the chart, use plt.title(<Title of the chart>) .

plt.title("This is example-2")

  • To add a label to X-axis, use plt.xlabel(<x-axis label name>) .

plt.xlabel("X-values")

  • To add a label to Y-axis, use plt.ylabel(<y-axis label name>) .

plt.ylabel("Y-values")

Code with X and Y labels and chart title

example2_code.PNG

Output

example2.png

Set Limits on X and Y axis

Use axis() function to set limit on x and y axis . The syntax is plt.axis(xmin, xmax, ymin, ymax).

example3_code.PNG

In above code we have set xmin = 10, xmax = 40, ymin = 5, ymax = 15

Output :

example3.png

Notice since the max limit on x axis is set to 40, the value for x=50 is not plotted.

Changing line color and type

The plot() function accepts a third argument which represents the color and type. By default, it is represented by a solid blue line. The syntax is mentioned below :

plt.plot([X-values], [Y-values], 'b-'

example4_code.PNG

In the above code :
'go' represents a green dotted
'rs' represents a red square
'b^' represents a blue triange
'y--' represents a yellow dashes

Output:

example4.png

Creating Bar Charts

Bar charts are created using bar() function.

bar_chart_1-code.PNG

In the above code, the plt.bar(x, y, alpha=0.8) creates a bar chart based on values of x and y.
alpha=0.8 represents the opacity of the bar. The value of alpha ranges from 0 to 1.

Output
bar_chart_1.png

The barh() function creates a horizontal bar chart.

barh(x, y, alpha=0.8)

bar_chart_2-code.PNG

Output

bar_chart_2.png

Creating Pie Charts

We can create pie chart using pie() function.

pie-chart-code.PNG

The above code, creates a pie chart based on the value of each items.
The area of whole chart represents 100% of data. The parts of the pie chart are called wedges. The area of wedges represents the percentage of each item with respect to the whole data.
By default the pie() function arranges the wedges in counter clockwise direction.

autopct parameter controls how the percentages are displayed in the wedges.

By default, the pie chart is in oval shape. To make it circular, we use plt.axis('equal').

pie-chart.png

Creating Donut Charts

To create a donut chart, we first create a pie chart and impose a white circle on top of it which makes it look like a donut.

The below code creates a white circle.

my_circle = plt.Circle((0, 0), 0.7, color='white')
p = plt.gcf()
p.gca().add_artist(my_circle)

Full code to create a donut.

donut-code.PNG

Output

donut.png

I have covered few basic charts that can be created using Matplotlib. There are several advance charts that can be created with this awesome tool which are used for data analysis and machine learning.I'll cover few of them in my next Matplotlib tutorial.



Posted on Utopian.io - Rewarding Open Source Contributors

Sort:  

Thank you for the contribution. It has been approved.

You can contact us on Discord.
[utopian-moderator]

Thank you.

Hey @rohancmr I am @utopian-io. I have just upvoted you!

Achievements

  • You have less than 500 followers. Just gave you a gift to help you succeed!
  • Seems like you contribute quite often. AMAZING!

Suggestions

  • Contribute more often to get higher and higher rewards. I wish to see you often!
  • Work on your followers to increase the votes/rewards. I follow what humans do and my vote is mainly based on that. Good luck!

Get Noticed!

  • Did you know project owners can manually vote with their own voting power or by voting power delegated to their projects? Ask the project owner to review your contributions!

Community-Driven Witness!

I am the first and only Steem Community-Driven Witness. Participate on Discord. Lets GROW TOGETHER!

mooncryption-utopian-witness-gif

Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x

Congratulations @rohancmr! You received a personal award!

1 Year on Steemit

Click here to view your Board

Support SteemitBoard's project! Vote for its witness and get one more award!

Congratulations @rohancmr! You received a personal award!

Happy Birthday! - You are on the Steem blockchain for 2 years!

You can view your badges on your Steem Board and compare to others on the Steem Ranking

Vote for @Steemitboard as a witness to get one more award and increased upvotes!