Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Path: blob/main/08. Data Visualization with Python/02. Exploring the Canada Immigration Dataset.ipynb
Views: 4585
Exploring the Canada Immigration Dataset with pandas
The first thing we'll do is import two key data analysis modules: pandas and numpy.
Let's download and import our primary Canadian Immigration dataset using pandas's read_csv()
method.
The file was originally downloaded from 'https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-DV0101EN-SkillsNetwork/Data Files/Canada.xlsx', and then prepared in the previous notebook.
Set the country name as index - useful for quickly looking up countries using .loc method
Select Column
There are two ways to filter on a column name:
Method 1: Quick and easy, but only works if the column name does NOT have spaces or special characters.
Method 2: More robust, and can filter on multiple columns.
Example: Let's try filtering on the list of countries ('Country').
Let's try filtering on the list of countries ('Country') and the data for years: 1980 - 1985.
Select Row
There are main 2 ways to select rows:
Before we proceed, notice that the default index of the dataset is a numeric range from 0 to 194. This makes it very difficult to do a query by a specific country. For example to search for data on Japan, we need to know the corresponding index value.
This can be fixed very easily by setting the 'Country' column as the index using set_index()
method.
Example: Let's view the number of immigrants from Japan (row 87) for the following scenarios: 1. The full row data (all columns) 2. For year 2013 3. For years 1980 to 1985
Column names that are integers (such as the years) might introduce some confusion. For example, when we are referencing the year 2013, one might confuse that when the 2013th positional index.
To avoid this ambuigity, let's convert the column names into strings: '1980' to '2013'.
Since we converted the years to string, let's declare a variable that will allow us to easily call upon the full range of years:
Filtering based on a criteria
To filter the dataframe based on a condition, we simply pass the condition as a boolean vector.
For example, Let's filter the dataframe to show the data on Asian countries (AreaName = Asia).
Before we proceed: let's review the changes we have made to our dataframe.
Matplotlib: Standard Python Visualization Library
The primary plotting library we will explore in the course is Matplotlib. As mentioned on their website:
Matplotlib is a Python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments across platforms. Matplotlib can be used in Python scripts, the Python and IPython shell, the jupyter notebook, web application servers, and four graphical user interface toolkits.
If you are aspiring to create impactful visualization with python, Matplotlib is an essential tool to have at your disposal.
Matplotlib.Pyplot
One of the core aspects of Matplotlib is matplotlib.pyplot
. It is Matplotlib's scripting layer which we studied in details in the videos about Matplotlib. Recall that it is a collection of command style functions that make Matplotlib work like MATLAB. Each pyplot
function makes some change to a figure: e.g., creates a figure, creates a plotting area in a figure, plots some lines in a plotting area, decorates the plot with labels, etc. In this lab, we will work with the scripting layer to learn how to generate line plots. In future labs, we will get to work with the Artist layer as well to experiment first hand how it differs from the scripting layer.
Let's start by importing matplotlib
and matplotlib.pyplot
as follows:
*optional: check if Matplotlib is loaded.
*optional: apply a style to Matplotlib.
Plotting in pandas
Fortunately, pandas has a built-in implementation of Matplotlib that we can use. Plotting in pandas is as simple as appending a .plot()
method to a series or dataframe.
Documentation:
What is a line plot and why use it?
A line chart or line plot is a type of plot which displays information as a series of data points called 'markers' connected by straight line segments. It is a basic type of chart common in many fields. Use line plot when you have a continuous data set. These are best suited for trend-based visualizations of data over a period of time.
Let's start with a case study:
In 2010, Haiti suffered a catastrophic magnitude 7.0 earthquake. The quake caused widespread devastation and loss of life and aout three million people were affected by this natural disaster. As part of Canada's humanitarian effort, the Government of Canada stepped up its effort in accepting refugees from Haiti. We can quickly visualize this effort using a Line
plot:
Question: Plot a line graph of immigration from Haiti using df.plot()
.
First, we will extract the data series for Haiti.
Next, we will plot a line plot by appending .plot()
to the haiti
dataframe.
pandas automatically populated the x-axis with the index values (years), and the y-axis with the column values (population). However, notice how the years were not displayed because they are of type string. Therefore, let's change the type of the index values to integer for plotting.
Also, let's label the x and y axis using plt.title()
, plt.ylabel()
, and plt.xlabel()
as follows:
We can clearly notice how number of immigrants from Haiti spiked up from 2010 as Canada stepped up its efforts to accept refugees from Haiti. Let's annotate this spike in the plot by using the plt.text()
method.
Quick note on x and y values in plt.text(x, y, label)
:
We can easily add more countries to line plot to make meaningful comparisons immigration from different countries.
Question: Let's compare the number of immigrants from India and China from 1980 to 2013.
Step 1: Get the data set for China and India, and display the dataframe.
Step 2: Plot graph. We will explicitly specify line plot by passing in kind
parameter to plot()
.
That doesn't look right...
Recall that pandas plots the indices on the x-axis and the columns as individual lines on the y-axis. Since df_CI
is a dataframe with the country
as the index and years
as the columns, we must first transpose the dataframe using transpose()
method to swap the row and columns.
pandas will auomatically graph the two countries on the same graph. Go ahead and plot the new transposed dataframe. Make sure to add a title to the plot and label the axes.
From the above plot, we can observe that the China and India have very similar immigration trends through the years.
Note: How come we didn't need to transpose Haiti's dataframe before plotting (like we did for df_CI)?
That's because haiti
is a series as opposed to a dataframe, and has the years as its indices as shown below.
class 'pandas.core.series.Series'
1980 1666
1981 3692
1982 3498
1983 2860
1984 1418
Name: Haiti, dtype: int64
Line plot is a handy tool to display several dependent variables against one independent variable. However, it is recommended that no more than 5-10 lines on a single graph; any more than that and it becomes difficult to interpret.
Question: Compare the trend of top 5 countries that contributed the most to immigration to Canada.
Other Plots
There are many other plotting styles available other than the default Line plot, all of which can be accessed by passing kind
keyword to plot()
. The full list of available plots are as follows:
bar
for vertical bar plotsbarh
for horizontal bar plotshist
for histogrambox
for boxplotkde
ordensity
for density plotsarea
for area plotspie
for pie plotsscatter
for scatter plotshexbin
for hexbin plot