fbpx

Graphing using Python and Matplotlib

"Close-up of a financial trading screen displaying live currency exchange rate graphs and market data, ideal for finance and stock market analysis."

In this article I will introduce you to graphing in python using matplotlib. There are many kinds of charts you can use with matplot lib. By the end of this article, you should understand how to draw basic bar, line, and scatterplot charts.

As you go through each of the example charts, you will see there are two arrays. These arrays are for the X and Y axis. And will sometimes include labels for the values on the chart.

Prerequisites

Before you get started, you will need to install the prerequisites. You can do that by running the following command:

pip3 install matplotlib
pip3 install numpy

Drawing a bar chart

Bar charts are good for comparing a small list of values. For example, perhaps you want to compare how many miles each person walked in the last week. We create a list of people, Matt, Sally, John. We then create a list of how many miles they walked. lets just say 1,2,3 respectively.

Below is the code for drawing our bar chart. See the comments for details:

import matplotlib.pyplot as plt

#Create a list showing how many miles each person walked

values = [1,2,3]

#Create a list of names
names = ["Matt","Sally","John"]

#Declare bar chart

plt.bar(values, values)

#Associate the names with the values
plt.xticks(values, names)

#Show the bar chart
plt.show()

The above code will produce the following chart:

"Bar chart comparing data values for Matt, Sally, and John with John having the highest value, visualizing statistical differences."

Drawing a line chart

A line chart is good for showing data over time, or showing the correlation between two values. In this case, we are just doing a generic line chart.

import matplotlib.pyplot as plt

#Declare line chart and pass in Y values for line

plt.plot([1,23,2,4])

#Declare the X values for the chart and assign labels to each of the points on the chart
plt.xticks([0,1,2,3],["one","two","three","four"])

#Assign a label to show on the left side of the chart
plt.ylabel('some numbers')

#Draw the chart
plt.show()

The above code will produce the following chart:

"Line graph showing data trend over categories one to four, with a peak at two and a decline at three, illustrating variable changes."

Drawing a Scatter Plot

Scatter plots are good for throwing a bunch of values onto a chart and see if any patterns emerge. You might find that there are clusters of values. Or you might find that the values form a line.

import matplotlib.pyplot as plt

#The next four lines of code simply draw spots on your chart. You can repeat this as many times as you want.

plt.scatter(1,2)
plt.scatter(2,3)
plt.scatter(3,5)
plt.scatter(4,3)

#Show the scatterplot
plt.show()

The above code will produce the following chart:

"Scatter plot displaying four colored data points, illustrating variable distribution across a coordinate grid."

The following code is similar to the above chart. However, in this example, we pass in an array of points to draw instead of drawing the points one at a time:

import matplotlib.pyplot as plt

#Declare an array showing the X and Y coordinates

x = [1, 2, 3, 4, 5, 6, 7]
y = [1, 3, 3, 2, 5, 7, 9]

#Pass all the points into the scatter plot
plt.scatter(x, y)

#Show the scatterplot on the screen

plt.show()

The above code will produce the following chart:

"Scatter plot depicting an upward trend with data points from one to seven on the x-axis, showing increasing values on the y-axis."

Draw a line showing the slope

As mentioned in the previous section, you might find that the scatter plots form a slope. The code below will calculate the slope of the line and draw it on your graph to help you spot a trend. You will notice that we are now including the NumPy module. NumPy is a module used for adding higher level mathematical functions to python as well as some features around multi-dimensional arrays.

[code language=”plain”][/code]

The above code will produce the following chart:

"Scatter plot with a blue regression line showing an upward trend, data points labeled from one to seven, indicating correlation strength of 1.21428571429."

Drawing a Pie Chart

In this section we will discuss how to draw a pie chart. Pie charts are good for showing how values relate to each other. In the code below, we create a simple pie chart:

import matplotlib.pyplot as plt

#Create list of values
values = [1,2,3]

#Create a list of names
names = ["Matt","Sally","John"]

#Declare pie chart
plt.pie(values,labels=names)

#Show pie chart
plt.show()

As you can see in the code above, we start by declaring two lists. One list consists of the values we plan to show in our pie chart. The second list is the labels associated with those values. We then declare our pie chart. And finally show the chart. When running the code above, you should see a result similar to this:

"Pie chart illustrating data distribution among Sally, Matt, and John, with sections in green, blue, and red, respectively."

If there is a particular value you want to bring some emphasis to, you can “explode” one of the pie slices. Exploding will push the slice out of the pie by some amount. To explode the pie, you have to pass in an explode value for each pie slide. In the code below, we have added a third list called explode. Then passed that into the chart declaration as an additional argument

#Exploded pie chart
import matplotlib.pyplot as plt

#Create list of values
values = [1,2,3]

#Create a list of names
names = ["Matt","Sally","John"]

explode = (0,0.1,0)

plt.pie(values,explode = explode, labels = names)

plt.show()

The code above should result in a chart looking similar to this:

"Exploded pie chart showing data distribution among Sally, Matt, and John with segments in green, blue, and red on a gray background."

Notice the value for Sally is moved out from the rest of the chart just a little bit. You can adjust the distance by adjusting the values in the explode list we declared.

Summary

Today we covered some of the charts you can draw using matplotlib in Python. You should now know how to create line, bar, pie, and scatterplot charts.

Elevate Your IT Efficiency with Expert Solutions

Transform Your Technology, Propel Your Business

Unlock advanced technology solutions tailored to your business needs. At Inventive HQ, we combine industry expertise with innovative practices to enhance your cybersecurity, streamline your IT operations, and leverage cloud technologies for optimal efficiency and growth.