Wednesday, January 1, 2020

Another simple plot

In this post we plot two (x;y) data sets: a smooth line curve and some data represented by red circles. In this plot, we label the x and y axes, create a legend, and draw lines to indicate where x and y are zero. The plot is shown below:



The code that creates this plot is shown below:

import numpy as np
import matplotlib.pyplot as plt

# read data from file
xdata, ydata = np.loadtxt('wavePulseData.txt', unpack=True)

# create x and y arrays for theory
x = np.linspace(-10., 10., 200)
y = np.sin(x) * np.exp(-(x/5.0)**2)

# create plot
plt.figure(1, figsize = (6,4) )
plt.plot(x, y, 'b-', label='theory')
plt.plot(xdata, ydata, 'ro', label="data")
plt.xlabel('x')
plt.ylabel('transverse displacement')
plt.legend(loc='upper right')
plt.axhline(color = 'gray', zorder=-1)
plt.axvline(color = 'gray', zorder=-1)

# save plot to file
plt.savefig('WavyPulse.pdf')

# display plot on screen
plt.show()

First, the script loads the NumPy and matplotlib modules, then reads data from a data file into two arrays, xdata and ydata, and then creates two more arrays, x and y. The first pair or arrays, xdata and ydata, contain the x-y data that are plotted as blue circles in Figure shown above; the arrays created in lines 8 and 9 contain the x-y data that are plotted as a green line.

The functions that create the plot begin on line 12. Let’s go through them one by one and see what they do. You will notice that keyword arguments (kwargs) are used in several cases.

figure() creates a blank figure window. If it has no arguments, it creates a window that is 8 inches wide and 6 inches high by default, although the size that appears on your computer depends on your
screen’s resolution. For most computers, it will be much smaller. You can create a window whose size differs from the default using the optional keyword argument figsize, as we have done here. If
you use figsize, set it equal to a 2-element tuple where the elements, expressed in inches, are the width and height, respectively, of the plot. Multiple calls to figure() opens multiple windows: figure(1) opens up one window for plotting, figure(2) another, and figure(3) yet another.

plot(x, y, optional arguments) graphs the x-y data in the arrays x and y. The third argument is a format string that specifies the color and the type of line or symbol that is used to plot the data. The string 'bo' specifies a blue (b) circle (o). The string 'g-' specifies a green (g) solid line (-). The keyword argument label is set equal to a string that labels the data if the legend function is called subsequently.

xlabel(string) takes a string argument that specifies the label for the graph’s x-axis.

ylabel(string) takes a string argument that specifies the label for the graph’s y-axis.

legend() makes a legend for the data plotted. Each x-y data set is labeled using the string that was supplied by the label keyword in the plot function that graphed the data set. The loc keyword argument specifies the location of the legend. The title keyword can be used to give the legend a title.

axhline() draws a horizontal line across the width of the plot at y=0. Writing axhline(y=a) draws a horizontal line at y=a, where y=a can be any numerical value. The optional keyword argument color is a string that specifies the color of the line. The default color is black. The optional keyword argument zorder is an integer that specifies which plotting elements are in front of or behind others. By default, new plotting elements appear on top of previously plotted elements and have a value of zorder=0. By specifying zorder=-1, the horizontal line is plotted behind all existing plot elements that
have not be assigned an explicit zorder less than 1. The keyword zorder can also be used as an argument for the plot function to specify the order of lines and symbols. Normally, for example,
symbols are placed on top of lines that pass through them.

axvline() draws a vertical line from the top to the bottom of the plot at x=0. See axhline() for an explanation of the arguments.

savefig(string) saves the figure to a file with a name specified by the string argument. The string argument can also contain path information if you want to save the file someplace other than the
default directory. Here we save the figure to a subdirectory named figures of the default directory. The extension of the filename determines the format of the figure file. The following formats are
supported: png, pdf, ps, eps, and svg.

show() displays the plot on the computer screen. No screen output is produced before this function is called.

To plot the solid blue line, the code uses the 'b-' format specifier in the plot function call. It is important to understand that matplotlib draws straight lines between data points. Therefore, the curve
will appear smooth only if the data in the NumPy arrays are sufficiently dense. If the space between data points is too large, the straight lines the plot function draws between data points will be visible. For plotting a typical function, something on the order of 100–200 data points usually produces a smooth curve, depending on just how curvy the function is. On the other hand, only two points are required to draw a smooth straight line.

Share:

Tuesday, December 31, 2019

Plotting the sine function

Let’s plot the sine function over the interval from 0 to 4 . The main plotting function plot in matplotlib
does not plot functions per se, it plots (x;y) data sets. As we shall see, we can instruct the function plot either to just draw points or dots at each data point, or we can instruct it to draw straight lines between the data points. To create the illusion of the smooth function that the sine function is, we need to create enough (x;y) data points so that when plot draws straight lines between the data points, the function appears to be smooth.

The sine function undergoes two full oscillations with two maxima and two minima between 0 and 4 . So let’s start by creating an array with 33 data points between 0 and 4 , and then let matplotlib draw a straight line between them. Our code consists of four parts:

• Import the NumPy and matplotlib modules.
• Create the (x;y) data arrays.
• Have plot draw straight lines between the (x;y) data points.
• Display the plot in a figure window using the show function.

See the following program:


import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 4.*np.pi, 33)
y = np.sin(x)
plt.plot(x, y)
plt.show()


The output is shown below. It consists of the sine function plotted over the interval from 0 to 4 , as advertised, as well as axes annotated with nice whole numbers over the appropriate interval.

One problem, however, is that while the plot oscillates like a sine wave, it is not smooth (look at the peaks). This is because we did not create the (x;y) arrays with enough data points. To correct this, we
need more data points which can be created using the same program shown above but with 129 (x;y) data points instead of 33. In the above program just replace 33 in line 3 with 129 (a few more or less is ok) so that the function linspace creates an array with 129 data points instead of 33. The output iss shown below:

In making this plot, matplotlib has made a number of choices, such as the size of the figure, the color of the line, even the fact that by default a line is drawn between successive data points in the (x;y) arrays. All of these choices can be changed by explicitly instructing matplotlib to do so. This involves including more arguments in the function calls we have used and using new functions that control other properties of the plot. See the previous posts and try a few of the simpler embellishments that are possible.


Share:

Monday, December 30, 2019

Introducing New Elements to a Plot

Charts are supposed to make your data visually appealing. To do this, it is important to ensure you use the correct chart to represent the data you need, because not all charts are suitable for any kind of data. The basic lines and markers will not be sufficient in making the charts appealing. You should think of getting additional elements into the chart for this purpose.

How to add text to a chart

With the title() function, you can introduce an elaborate title into the chart. Beyond that, you should also be able to introduce the axis label. This is done with the xlabel() and ylabel() functions. Remember that when you introduce a new function like the axis label functions, they create an argument within the string of code you are working with. We want to introduce the axis labels to a chart. This is the first step because they help you identify the values that will be assigned to every axis as you plot data. Your illustration should follow the code below:

import matplotlib.pyplot as plt
plt.axis([0,5,0,20])
plt.title('My first plot')
plt.xlabel('Counting')
plt.ylabel('Square values')
plt.plot([1,2,3,4], [1,4,9,16],'ro')
plt.show()


When you run the above program you should have the following plot:

You can perform basic editing for all the text you have entered that describe the plot. Basic editing includes altering the font and font size, colors, or any other tweaks that you might need for the plot to be appealing. Following the example above, we can further tweak the title as follows:

plt.axis([0,5,0,20])
plt.title('My first plot',fontsize=18,fontname='Comic Sans MS')
plt.xlabel('Counting',color='black')
plt.ylabel('Square values',color='black')
plt.plot([1,2,3,4], [1,4,9,16],'ro')
plt.show()


The output should be as shown below:







The Matplotlib functionality allows you to perform more edits to the chart. For example, you can introduce new text into the chart using the text () function,

text(x,y,s, fontdict=None, **kwargs) .


In the function outlined above, the coordinates x and y represent the location of the text you are introducing into the chart. s, represents the string of text you are adding to the chart at the specified location. The fontdict() function represents the font you use for the new text. However, this function is optional. Once you have these figured out, you can then introduce keywords into the code. Let’s
have a look at the example below to illustrate this:

plt.axis([0,5,0,20])
plt.title('My first plot',fontsize=20,fontname='Times New Roman')
plt.xlabel('Counting',color='gray')
plt.ylabel('Square values',color='gray')
plt.text(1,1.4,'First')
plt.text(2,4.4,'Second')
plt.text(3,9.4,'Third')
plt.text(4,16.4,'Fourth')
plt.plot([1,2,3,4], [1,4,9,16],'ro')
plt.show()


The output should be as shown below:

Matplotlib is specifically built to help you introduce mathematical expressions into your work using the LaTeX expressions. When keyed in correctly, the interpreter will recognize the expressions and aptly convert them into the necessary expression graphic. This is how to introduce formula, expressions, or other unique characters into your plot. When writing LaTeX expressions, remember to use an r before the expression so that the interpreter can read it as raw text.

plt.axis([0,5,0,20])
plt.title('My first plot',fontsize=20,fontname='Times New Roman')
plt.xlabel('Counting',color='gray')
plt.ylabel('Square values',color='gray')
plt.text(1,1.4,'First')
plt.text(2,4.4,'Second')
plt.text(3,9.4,'Third')
plt.text(4,16.4,'Fourth')
plt.text(1.1,12,r'$y = x^2$',fontsize=20,bbox={'facecolor':'yellow','alpha':0.2})
plt.plot([1,2,3,4], [1,4,9,16],'ro')
plt.show()


Your plot should have a y=x2 expression in a yellow background as shown below:

 More often, you can go online and create charts that allow you to automatically add or remove grids. You can do this in Python, too. A grid is important in your work because it shows you the position of all the points plotted on the chart. To add a grid, introduce the grid() function as shown below, passing it as true.

plt.axis([0,5,0,20])
plt.title('My first plot',fontsize=20,fontname='Times New Roman')
plt.xlabel('Counting',color='gray')
plt.ylabel('Square values',color='gray')
plt.text(1,1.4,'First')
plt.text(2,4.4,'Second')
plt.text(3,9.4,'Third')
plt.text(4,16.4,'Fourth')
plt.text(1.1,12,r'$y = x^2$',fontsize=20,bbox={'facecolor':'yellow','alpha':0.2})
plt.grid(True)
plt.plot([1,2,3,4], [1,4,9,16],'ro')
plt.show()




The output is as shown below:



If you want to do away with the grid, you should plot the condition as false as shown below:

plt.grid(True)



Share:

Sunday, December 29, 2019

How to Create a Chart

Before you begin, import pyplot to your programming environment and set the name as plt as shown below:

import matplotlib.pyplot as plt
plt.plot([1,2,3,4])


When you enter this code, you will have created a Line2D object. An object in this case is a linear representation of the trends you will plot within a given chart. To view the plot, you will use the function below:

plt.show()

The result should be a plotting window similar to the one below:



Depending on the platform you are using, in some cases your chart will display without necessarily calling the show() function, especially if you are using iPython QtConsole. Once this plot is prepared you must provide a definition for the two arrays on the x and y axis. The blue line in the example above represents all the points in your plot. This is the default configuration when your data does not have a legend, axis labels, or a title.

Beyond using pyplot commands for single figures, you can work with lots of figures at the same time in Matplotlib. You can take things further and introduce new plots within each figure. Other than using multiple subplots, you can also use the subplot() function to create multiple drawing areas in the main figure.

The subplot() function also helps you choose the subplot to focus your work on. Once selected, any commands passed will be called on the current subplot. A careful look at the subplot() function reveals three integers, each of which serves a unique role.

The first integer outlines the number of vertical divisions available in the figure. The second integer outlines the number of horizontal divisions available in the figure. The third integer outlines the subplot where your commands are directed.

t = np.arange(0,5,0.1)
y1 = np.sin(2*np.pi*t)
y2 = np.sin(2*np.pi*t)
plt.subplot(211)
plt.plot(t,y1,'b-.')
plt.subplot(212)
plt.plot(t,y2,'r--')

You should have the following plot:



In the next example, we will create vertical divisions from the plots above using the code below:

t = np.arange(0.,1.,0.05)
y1 = np.sin(2*np.pi*t)
y2 = np.cos(2*np.pi*t)

plt.subplot(121)
plt.plot(t,y1,'b-.')
plt.subplot(122)
plt.plot(t,y2,'r--')
plt.show()

You should have the plot below:





Share:

Saturday, December 28, 2019

Display Tools in Matplotlib

There are different display tools you can use to help you understand a plot the first time you see it. Legends and annotations serve this purpose. Legends identify different series of data within your plot. To access it, you call the matplotlib function legend () .

Annotations, on the other hand, help in identifying the important points in the plot. Annotations are called using the matplotlib function annotate() . An annotation must always have an arrow and a label, each of which could be described by different parameters. Because of this reason, you can use the help (annotate) function to get the best explanation.

Other display tools include labels, grids, and titles. A label will be present on both axes, but you can call them using the functions xlabel () and ylabel () for the x and y axis respectively. The title of your plot can be identified using the title () function, while the grid is identified using the grid () function. It is wise to note that you can turn the grid plot on or off where necessary.

In Matplotlib, you will be working with a lot of tools and functions that enhance manipulation and representation of the objects you work with, alongside any internal objects that might be present. By design, matplotlib is built into three layers as shown below:

● The scripting layer

This layer is also referred to as the pyplot . This is where functions and artist classes operate. The pyplot is an interface used in data visualization and analysis.

● The artist layer


This is an intermediate Matplotlib layer. All the elements in this layer are used in building charts, and include things like markers, titles, and labels assigned to the x and y axis.

● The backend layer

This is the lowest level in Matplotlib. All the APIs are found in this layer. At this point, graphic element implementation takes place, albeit at the lowest possible level. Each of these layers can only share communication with the layer beneath it, but not the one above it, hence the nature of communication in Matplotlib is unidirectional.

Having mentioned pyplot , you should also learn about pylab . Pylab is a unique module that is installed together with Matplotlib, while pyplot on the other hand runs as an internal package in Matplotlib. Your installation code for these two will look like this:

from pylab import *
and
import matplotlib.pyplot as plt
import numpy as np


Pylab allows you to enjoy the benefits of using pyplot and NumPy within the same namespace, without necessarily having to import NumPy as a separate package. If you already have pylab imported, you will not need to call the NumPy and pyplot functions because they are automatically called, in a process similar to what you experience in MATLAB as shown below:

Instead of having
plt.plot()
np.array([1,2,3,4]


You will have
plot(x,y)
array([1,2,3,4])


Essentially, the role of the pyplot package is to enable you to program in Python through the matplotlib library.
Share:

Friday, December 27, 2019

Scatter Plots

The role of a scatter plot is to identify the relationship between a couple of variables displayed in a coordinate system. Each data point is identified according to the variable values. From the scatter graph, you can tell whether there is a relationship between the variables or not.

When studying a scatter plot diagram, the direction of the trend tells you the nature of correlation. A positive correlation, for example, is represented by an upward pattern. A scatter plot can also be used alongside a bubble chart. Bubble charts introduce a third variable beyond the two identified in the scatter plot. The size of the bubble around the data points is used to determine the value of the third variable.

In matplotlib, scatter plots are called through the scatter () function. The following commands are used to access the scatter function’s documentation:

$ ipython -pylab
In [1] : help(scatter)

In the example below, we introduce three parameters, s to represent the size of the bubble chart, alpha to represent the transparency of the bubbles when plotted on the chart, and c to represent the colors. The alpha variable values are in the range of 0 - completely transparent, and 1 - completely opaque. You will have a scatter chart with the following coordinates:

plt.scatter(years, cnt_log, c= 200 * years, s=20 + 200 *
gpu_counts/gpu_counts.max(), alpha=0.5)

You should have the following code:

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
df = pd.read_csv('transcount.csv')
df = df.groupby('year').aggregate(np.mean)
gpu = pd.read_csv('gpu_transcount.csv')
gpu = gpu.groupby('year').aggregate(np.mean)
df = pd.merge(df, gpu, how='outer', left_index=True, right_index=True)
df = df.replace(np.nan, 0)
print df
years = df.index.values
counts = df['trans_count'].values
gpu_counts = df['gpu_trans_count'].values
cnt_log = np.log(counts)
plt.scatter(years, cnt_log, c= 200 * years, s=20 + 200 * gpu_counts/
gpu_counts.max(), alpha=0.5)
plt.show()


The output as obtained on the output window is as follows-

       trans_count  gpu_trans_count
year
1971  2.300000e+03     0.000000e+00
1972  3.500000e+03     0.000000e+00
1974  4.533333e+03     0.000000e+00
1975  3.510000e+03     0.000000e+00
1976  7.500000e+03     0.000000e+00
1978  1.900000e+04     0.000000e+00
1979  4.850000e+04     0.000000e+00
1982  9.450000e+04     0.000000e+00
1983  8.500000e+03     0.000000e+00
1984  2.000000e+05     0.000000e+00
1985  1.053333e+05     0.000000e+00
1986  2.500000e+04     0.000000e+00
1988  2.500000e+05     0.000000e+00
1989  7.401175e+05     0.000000e+00
1991  6.900000e+05     0.000000e+00
1993  3.100000e+06     0.000000e+00
1994  5.789770e+05     0.000000e+00
1995  5.500000e+06     0.000000e+00
1996  4.300000e+06     0.000000e+00
1997  8.150000e+06     3.500000e+06
1998  7.500000e+06     0.000000e+00
1999  1.760000e+07     1.350000e+07
2000  3.150000e+07     2.500000e+07
2001  4.500000e+07     5.850000e+07
2002  1.375000e+08     8.500000e+07
2003  1.900667e+08     1.260000e+08
2004  3.520000e+08     1.910000e+08
2005  1.690000e+08     3.120000e+08
2006  6.040000e+08     5.325000e+08
2007  3.716000e+08     7.270000e+08
2008  9.032000e+08     1.179500e+09
2009  3.450000e+09     2.154000e+09
2010  1.511667e+09     2.946667e+09
2011  1.733500e+09     4.312712e+09
2012  2.014826e+09     5.310000e+09
2013  5.000000e+09     6.300000e+09
2014  4.310000e+09     0.000000e+00

 

The following plot will be obtained-


Share:

Thursday, December 26, 2019

Logarithmic Plots (Log Plots)

A logarithmic plot is essentially a basic plot, but it is set on a logarithmic scale. The difference between this and a normal linear scale is that the intervals are set in order of their magnitude. We have two different types of log plots: the log-log plot and semi-log plot.

The log-log plot has logarithm scales on both the x and y axis. In matplotlib, this plot is identified by the following function: matplotlib.pyplot.loglog() . The semi-log plot, on the other hand, uses two different scales. It has a logarithmic scale on one axis and a linear scale on the other. They are identified by the following functions:

semilogx() for the x axis, and semilogy() for the y axis.

Straight lines in such plots are used to identify exponential laws. The code below represents data on transistor counts within a given range of years. We will use it to study the procedure for creating logarithmic plots:


import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
df = pd.read_csv('transcount.csv')
df = df.groupby('year').aggregate(np.mean)
years = df.index.values
counts = df['trans_count'].values
poly = np.polyfit(years, np.log(counts), deg=1)
print ("Poly", poly)
plt.semilogy(years, counts, 'o')
plt.semilogy(years, np.exp(np.polyval(poly, years)))
plt.show()


Step 1:

Build the data using the following functions:

poly = np.polyfit(years, np.log(counts), deg=1)
print "Poly", poly

Step 2:

From the data fit above, you should have a polynomial object. Based on the data available, you should have the polynomial coefficients arranged in descending order.

Step 3:

To study the polynomial created, use the NumPy function polyval() . Plot data and use the y axis semi-log function as shown:

plt.semilogy(years, counts, 'o')
plt.semilogy(years, np.exp(np.polyval(poly, years)))

Now run the program, you will get the following plot:

Also, Poly [ 3.61559210e-01 -7.05783195e+02] will be printed on the output window.

Share:

Wednesday, December 25, 2019

Basic Matplotlib Plots

A simple plot

Before you plot on matplotlib, you must have a plot () function within the matplotlib.pyplot sub package. This is to give you the basic plot with x-axis and y-axis variables. Alternatively, you can also use format parameters to represent the line style you are using. To determine the format parameters and options used, the following commands apply:

$ ipython -pylab
In [1] : help(plot)

In the example above, you are creating two unique lines. The first one, which will act as the default line, is the solid line style, while the second one will have a dashed line. Study the code snippet below. We will use it to describe the procedure on how to create a simple plot.

import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 20)
plt.plot(x, .5 + x)
plt.plot(x, 1 + 2 * x, '--')
plt.show()


Use the following procedure to plot the lines described above:


Step 1:

Determine the x coordinates using linspace () , a NumPy function. The x coordinates start at 0 and end at 20, hence you should have the following function:

x = np.linspace(0, 20)

Step 2:

Plot the lines on your axis in the following order:

plt.plot(x, .5 + x)
plt.plot(x, 1 + 2 * x, '--')

Step 3:

At this point, you have two options. You can save the plot or view it on a screen. The savefig() function is used to save the file. If you have to view it, the show () function is used. To view the function on the screen, use the following plotting function:

plt.show()

The plot obtained is shown below:

Share:

Tuesday, December 24, 2019

Fundamentals of Matplotlib

Lets look at some of the important concepts that you shall come across and use in Matplotlib, and their meanings or roles:
  • Axis – This represents a number line, and is used to determine the graph limits.
  • Axes – These represent what we construe as plots. A single figure can hold as many axes as  possible. In the event of a 3D object, you can have two or three objects. Take note that for all axes, you must have an x and y label.
  • Artist – Refers to everything that you can see on your figure, for example collection objects, Line2D objects and Text objects. You will notice that most of the Artists are on the Axes.
  • Figure – Refers to the entire figure you are working on. It might include more than one plots or axes.
Pyplot is a Matplotlib module that allows you to work with simple functions, in the process adding elements like text, images, and lines within the figure you are working on. A simple plot can be created in the following manner:

import matplotlib.pyplot as plt
import numpy as np


There are lots of command functions that you can use to help you work with Matplotlib. Each of these pyplot functions changes figures in one way or the other when executed. The following is a list of the plots you will use in Matplotlib:

● Quiver – Used to create 2D arrow fields
● Step – Used to create a step plot
● Stem – Used to build a stem plot
● Scatter – Creates a scatter plot of x against y
● Stackplot – Used to create a plot for a stacked area
● Plot – Creates markers or plot lines to your axes
● Polar – Creates a polar plot
● Pie – Creates a pie chart
● Barh - Creates a horizontal bar plot
● Bar – Creates a bar plot
● Boxplot – Creates a whisker and box plot
● Hist – Used to create a histogram
● Hist2d – Used to create a histogram plot in 2D

Given that you might be working with images from time to time during data analysis, you will frequently use the following image functions:

● Imshow – Used to show images on your axes
● Imsave – Used to save arrays in the form of an image file
● Imread – Used to read files from images into arrays

Now it's time to create a plot but you must first import the Pyplot module from your Matplotlib package before you can create a plot. This is done as shown below:

import matplotlib.pyplot as plt

After importing the module, you introduce arrays into the plot. The NumPy library has predefined array functions that you will use going forward. These are imported as follows:

import numpy as np

With this done, proceed to introduce objects into the plot using the NumPy library’s arange() function as shown below:

x = np.arange(0, math.pi*2, 0.05)

With this data, you can then proceed to specify the x and y axis labels, and the plot title as shown:

plt.xlabel("angle")
plt.ylabel("sine")
plt.title('sine wave')


To view the window, use the show() function below:

plt.show()

At this juncture, your program should look like this:

from matplotlib import pyplot as plt
import numpy as np
import math #will help in defining pi
x = np.arange(0, math.pi*2, 0.05)
y = np.sin(x)
plt.plot(x,y)
plt.xlabel("angle")
plt.ylabel("sine")
plt.title('sine wave')
plt.show()


Before you plot on matplotlib, you must have a plot () function within the matplotlib.pyplot subpackage. This is to give you the basic plot with x-axis and y-axis variables. Now run the program and see the plot obtained. It should be like:


Share:

Monday, December 23, 2019

Data Visualization with Matplotlib

Data visualization is one of the first things you have to perform before you analyze data. The moment you have a glance at some data, your mind creates a rough idea of the way you want it to look when you map it on a graph.

Image result for data visualization with matplotlib in python

Matplotlib might seem rather complex at first, but with basic coding knowledge, it should be easier for you. We will highlight some of the important concepts that will guide your work going forward.


Plotting data for visualization will need you to work with different data ranges. You might need to work with general or specific data ranges. The whole point behind Matplotlib is to help you work with data with as minimal challenges as possible. As a data analyst, you are in full control over the data you use, hence you must also understand the necessary commands to alter the same.

Remember that the machine learning environment in Matplotlib is almost similar to MATLAB. Therefore, if you have some experience with MATLAB, you should find things easier here. All the work you do in Matplotlib is built in a hierarchical manner. At the highest point, you have a state-machine environment, while at the lowest level you have the object-oriented interfaces where pyplot only performs a limited number of functions. At this level, it is up to you to build figures, and from them you can create axes. The axes will help in all, if not most of your plotting needs.

To install Matplotlib on your machine, run the following Python command:

python -m pip install -U pip
python -m pip install -U matplotlib

To set you off, install Matplotlib on your device using the following commands:

pip install matplotlib
xcode-select -install (if you are working on a Mac)

There are several dependencies that you might need to install with Matplotlib, including NumPy and Python if it is not already installed on your device. To further enhance your interface output, you might also need to install other packages like Tornado and pycairo.

If you are going to work on animations from time to time, you might need to install ImageMagick or any other packages that could assist you like LaTeX.

Fundamentals of Matplotlib

Below are some of the important concepts that you shall come across and use in Matplotlib, and their meanings or roles:

● Axis – This represents a number line, and is used to determine the graph limits.
● Axes – These represent what we construe as plots. A single figure can hold as many axes as possible. In the event of a 3D object, you can have two or three objects. Take note that for all axes, you must have an x and y label.
● Artist – Refers to everything that you can see on your figure, for example collection objects, Line2D objects and Text objects. You will notice that most of the Artists are on the Axes.
● Figure – Refers to the entire figure you are working on. It might include more than one plots or axes.

Pyplot is a Matplotlib module that allows you to work with simple functions, in the process adding elements like text, images, and lines within the figure you are working on. A simple plot can be created in the following manner:

import matplotlib.pyplot as plt
import numpy as np
Share:

Saturday, December 21, 2019

How to Avoid Data Contamination

From empty data fields to data duplication and invalid addresses, there are so many ways you can end up with contaminated data. Having looked at possible causes and methods of cleaning data, it is important for an expert in your capacity to put measures in place to prevent data contamination in the future. The challenges you experienced in cleaning data could easily be avoided, especially if the data collection processes are within your control.




Looking back to the losses your business suffers in dealing with contaminated data and the resource wastage in terms of time, you can take significant measures to reduce inefficiencies, which will eventually have an impact on your customers and their level of satisfaction.

One of the most important steps today is to invest in the appropriate CRM programs to help in data handling. Having data in one place makes it easier to verify the credibility and integrity of data within your database. The following are some simple methods you can employ in your organization to prevent data contamination, and ensure you are using quality data for decision-making:


● Proper configurations

Irrespective of the data handling programs you use, one of the most important things is to make sure you configure applications properly. Your company could be using CRM programs or simple Excel sheets. Whichever the case, it is important to configure your programs properly. Start with the critical information. Make sure the entries are accurate and complete. One of the challenges of incomplete data is that there is always the possibility that someone could complete them with inaccurate data to make them presentable, when this is not the real picture.

Data integrity is just as important, so make sure you have the appropriate data privileges in place for anyone who has to access critical information. Set the correct range for your data entries. This way, anyone keying in data will be unable to enter incorrect data not within the appropriate range. Where possible, set your system up such that you can receive notifications whenever someone enters the wrong range, or is struggling, so that you can follow up later on and ensure you captured the correct data.


● Proper training


Human error is one of a data analyst’s worst nightmares when trying to prevent data contamination. Other than innocent mistakes, many errors from human entry are usually about context. It is important that you train everyone handling data on how to go about it. This is a good way to improve accuracy and data integrity from the foundation - data entry.

Your team must also understand the challenges you experience when using contaminated data, and more importantly why they need to be keen at data entry. If you are using CRM programs, make sure they understand different functionality levels so they know the type of data they should enter.

Another issue is how to find the data they need. When under duress, most people key in random or inaccurate data to get some work done or bypass some restrictions. By training them on how to search for specific data, it is easier to avoid unnecessary challenges with erroneous entries. This is usually a problem when you have new members joining your team. Ensure you train them accordingly, and encourage them to ask for help whenever they are unsure of anything.


● Entry formats

The data format is equally important as the desired level of accuracy. Think about this from a logical perspective. If someone sends you a text message written in all capital letters, you will probably disregard it or be offended by the tone of the message. However, if the same message is sent with proper formatting, your response is more positive.

The same applies to data entry. Try and make sure that everyone who participates in data handling is careful enough to enter data using the correct format. Ensure the formats are easy to understand, and remind the team to update data they come across if they realize it is not in the correct format. Such
changes will go a long way in making your work easier during analysis.

● Empower data handlers

Beyond training your team, you also need to make sure they are empowered and aware of their roles in data handling. One of the best ways of doing this is to assign someone the data advocacy role. A data advocate is someone whose role is to ensure and champion consistency in data handling. Such a person will essentially be your data administrator. Their role is usually important, especially when implementing new systems. They come up with a plan to ensure data is cleaned and organized. One of their deliverables should include proper data collection procedures to help you improve the results obtained from using the data in question.

● Overcoming data duplication


Data duplication happens in so many organizations because the same data is processed at different levels. Duplication might eventually see you discard important and accurate data accidentally, affecting any results derived from the said data. For example, ensure your team searches for specific items before they create new ones. Provide an in-depth search process that increases the search results and reduces the possibility of data duplication. For example, beyond looking for a customer’s name, the entry should also include contact information.

Provide as many relevant fields that can be searched into, thereby increasing the possibility of arresting and avoiding duplicates. You can find data for a customer named COVRI Solutions PVT LTD in different databases labeled as COVRI SOLUTIONS P LTD or COVRI Solutions PVT LT. The moment you come across such duplicates, the last thing you want to do is to eliminate them from the database. Instead, investigate further to ascertain the similarities and differences between the entries.

Consult, verify, and update the correct entry accordingly. Alternatively, you can escalate such issues to your data advocate for further action. At the same time, put measures in place that scans your database to warn users whenever they are about to create a duplicate entry.

● Data filtration

Perhaps one of the best solutions would be cleaning data before it gets into your database. A good way of doing this would be creating clear outlines on the correct data format to use. With such procedures in place, you have an easier time handling data. If all the conditions are met, you will probably handle data cleaning at the entry point instead of once the data is in your database, making
your work easier.

Create filters to determine the right data to collect and the data that can be updated later. It doesn’t make sense to collect a lot of information to give you the illusion of a complete and elaborate database, when in a real sense very little of what you have is relevant to your cause.

The misinformation that arises from inaccurate data can be avoided if you take the right precautionary measures in data handling. Data security is also important, especially if you are using data sources where lots of other users have access. Restrict access to data where possible, and make sure you create different access privileges for all users.






Share: