# How to Sort a List of Tuples in Python

This chapter is from the book

## 5.17 Intro to Data Science: Simulation and Static Visualizations

The last few chapters’ Intro to Data Science sections discussed basic descriptive statistics. Here, we focus on visualizations, which help you “get to know” your data. Visualizations give you a powerful way to understand data that goes beyond simply looking at raw data.

We use two open-source visualization libraries—Seaborn and Matplotlib—to display static bar charts showing the final results of a six-sided-die-rolling simulation. The Seaborn visualization library is built over the Matplotlib visualization library and simplifies many Matplotlib operations. We’ll use aspects of both libraries, because some of the Seaborn operations return objects from the Matplotlib library. In the next chapter’s Intro to Data Science section, we’ll make things “come alive” with dynamic visualizations.

### 5.17.1 Sample Graphs for 600, 60,000 and 6,000,000 Die Rolls

The screen capture below shows a vertical bar chart that for 600 die rolls summarizes the frequencies with which each of the six faces appear, and their percentages of the total. Seaborn refers to this type of graph as a bar plot:

Here we expect about 100 occurrences of each die face. However, with such a small number of rolls, none of the frequencies is exactly 100 (though several are close) and most of the percentages are not close to 16.667% (about 1/6th). As we run the simulation for 60,000 die rolls, the bars will become much closer in size. At 6,000,000 die rolls, they’ll appear to be exactly the same size. This is the “law of large numbers” at work. The next chapter will show the lengths of the bars changing dynamically.

We’ll discuss how to control the plot’s appearance and contents, including:

• the graph title inside the window (Rolling a Six-Sided Die 600 Times),

• the descriptive labels Die Value for the x-axis and Frequency for the y-axis,

• the text displayed above each bar, representing the frequency and percentage of the total rolls, and

• the bar colors.

We’ll use various Seaborn default options. For example, Seaborn determines the text labels along the x-axis from the die face values 1–6 and the text labels along the y-axis from the actual die frequencies. Behind the scenes, Matplotlib determines the positions and sizes of the bars, based on the window size and the magnitudes of the values the bars represent. It also positions the Frequency axis’s numeric labels based on the actual die frequencies that the bars represent. There are many more features you can customize. You should tweak these attributes to your personal preferences.

The first screen capture below shows the results for 60,000 die rolls—imagine trying to do this by hand. In this case, we expect about 10,000 of each face. The second screen capture below shows the results for 6,000,000 rolls—surely something you’d never do by hand! In this case, we expect about 1,000,000 of each face, and the frequency bars appear to be identical in length (they’re close but not exactly the same length). Note that with more die rolls, the frequency percentages are much closer to the expected 16.667%.

### 5.17.2 Visualizing Die-Roll Frequencies and Percentages

In this section, you’ll interactively develop the bar plots shown in the preceding section.

#### Launching IPython for Interactive Matplotlib Development

IPython has built-in support for interactively developing Matplotlib graphs, which you also need to develop Seaborn graphs. Simply launch IPython with the command:

`     ipython --matplotlib`

#### Importing the Libraries

First, let’s import the libraries we’ll use:

```In [1]: import matplotlib.pyplot   as plt

In [2]: import numpy as np

In [3]: import random

In [4]: import seaborn as sns```
1. The matplotlib.pyplot module contains the Matplotlib library’s graphing capabilities that we use. This module typically is imported with the name plt.

2. The NumPy (Numerical Python) library includes the function unique that we’ll use to summarize the die rolls. The numpy module typically is imported as np.

3. The random module contains Python’s random-number- generation functions.

4. The seaborn module contains the Seaborn library’s graphing capabilities we use. This module typically is imported with the name sns. Search for why this curious abbreviation was chosen.

#### Rolling the Die and Calculating Die Frequencies

Next, let’s use a list comprehension to create a list of 600 random die values, then use NumPy’s unique function to determine the unique roll values (most likely all six possible face values) and their frequencies:

```In [5]: rolls = [random.randrange(1,   7) for i in range(600)]

In [6]: values, frequencies = np.unique(rolls,   return_counts=True)```

The NumPy library provides the high-performance ndarray collection, which is typically much faster than lists.1 Though we do not use ndarray directly here, the NumPy unique function expects an ndarray argument and returns an ndarray. If you pass a list (like rolls), NumPy converts it to an ndarray for better performance. The ndarray that unique returns we’ll simply assign to a variable for use by a Seaborn plotting function.

Specifying the keyword argument return_counts=True tells unique to count each unique value’s number of occurrences. In this case, unique returns a tuple of two one-dimensional ndarrays containing the sorted unique values and the corresponding frequencies, respectively. We unpack the tuple’s ndarrays into the variables values and frequencies. If return_counts is False, only the list of unique values is returned.

#### Creating the Initial Bar Plot

Let’s create the bar plot’s title, set its style, then graph the die faces and frequencies:

```In [7]: title = f'Rolling a Six-Sided   Die {len(rolls):,} Times'

In [8]: sns.set_style('whitegrid')

In [9]: axes = sns.barplot(x=values, y=frequencies,   palette='bright')```

Snippet [7]’s f-string includes the number of die rolls in the bar plot’s title. The comma (,) format specifier in

`     {len(rolls):,}`

displays the number with thousands separators—so, 60000 would be displayed as 60,000.

By default, Seaborn plots graphs on a plain white background, but it provides several styles to choose from ('darkgrid', 'whitegrid', 'dark', 'white' and 'ticks'). Snippet [8] specifies the 'whitegrid' style, which displays light-gray horizontal lines in the vertical bar plot. These help you see more easily how each bar’s height corresponds to the numeric frequency labels at the bar plot’s left side.

Snippet [9] graphs the die frequencies using Seaborn’s barplot function. When you execute this snippet, the following window appears (because you launched IPython with the --matplotlib option):

Seaborn interacts with Matplotlib to display the bars by creating a Matplotlib Axes object, which manages the content that appears in the window. Behind the scenes, Seaborn uses a Matplotlib Figure object to manage the window in which the Axes will appear. Function barplot’s first two arguments are ndarrays containing the x-axis and y-axis values, respectively. We used the optional palette keyword argument to choose Seaborn’s predefined color palette 'bright'. You can view the palette options at:

`https://seaborn.pydata.org/tutorial/color_palettes.html`

Function barplot returns the Axes object that it configured. We assign this to the variable axes so we can use it to configure other aspects of our final plot. Any changes you make to the bar plot after this point will appear immediately when you execute the corresponding snippet.

#### Setting the Window Title and Labeling the x- and y-Axes

The next two snippets add some descriptive text to the bar plot:

```In [10]: axes.set_title(title)
Out[10]: Text(0.5,1,'Rolling a Six-Sided Die 600 Times')

In [11]: axes.set(xlabel='Die Value',   ylabel='Frequency')
Out[11]: [Text(92.6667,0.5,'Frequency'), Text(0.5,58.7667,'Die   Value')]```

Snippet [10] uses the axes object’s set_title method to display the title string centered above the plot. This method returns a Text object containing the title and its location in the window, which IPython simply displays as output for confirmation. You can ignore the Out[]s in the snippets above.

Snippet [11] add labels to each axis. The set method receives keyword arguments for the Axes object’s properties to set. The method displays the xlabel text along the x-axis, and the ylabel- text along the y-axis, and returns a list of Text objects containing the labels and their locations. The bar plot now appears as follows:

#### Finalizing the Bar Plot

The next two snippets complete the graph by making room for the text above each bar, then displaying it:

```In [12]: axes.set_ylim(top=max(frequencies) * 1.10)
Out[12]: (0.0, 122.10000000000001)

In [13]: for bar, frequency in zip(axes.patches, frequencies):
...:     text_x = bar.get_x() + bar.get_width() / 2.0
...:     text_y = bar.get_height()
...:     text = f'{frequency:,}\n{frequency / len(rolls):.3%}'
...:     axes.text(text_x, text_y, text,
...:               fontsize=11,   ha='center', va='bottom')
...:              ```

To make room for the text above the bars, snippet [12] scales the y-axis by 10%. We chose this value via experimentation. The Axes object’s set_ylim method has many optional keyword arguments. Here, we use only top to change the maximum value represented by the y-axis. We multiplied the largest frequency by 1.10 to ensure that the y-axis is 10% taller than the tallest bar.

Finally, snippet [13] displays each bar’s frequency value and percentage of the total rolls. The axes object’s patches collection contains two-dimensional colored shapes that represent the plot’s bars. The for statement uses zip to iterate through the patches and their corresponding frequency values. Each iteration unpacks into bar and frequency one of the tuples zip returns. The for statement’s suite operates as follows:

• The first statement calculates the center x-coordinate where the text will appear. We calculate this as the sum of the bar’s left-edge x-coordinate (bar.get_x()) and half of the bar’s width (bar.get_width() / 2.0).

• The second statement gets the y-coordinate where the text will appear—bar.get_y() represents the bar’s top.

• The third statement creates a two-line string containing that bar’s frequency and the corresponding percentage of the total die rolls.

• The last statement calls the Axes object’s text method to display the text above the bar. This method’s first two arguments specify the text’s x–y position, and the third argument is the text to display. The keyword argument ha specifies the horizontal alignment—we centered text horizontally around the x-coordinate. The keyword argument va specifies the vertical alignment—we aligned the bottom of the text with at the y-coordinate. The final bar plot is shown below:

#### Rolling Again and Updating the Bar Plot—Introducing IPython Magics

Now that you’ve created a nice bar plot, you probably want to try a different number of die rolls. First, clear the existing graph by calling Matplotlib’s cla (clear axes) function:

`     In [14]: plt.cla()`

IPython provides special commands called magics for conveniently performing various tasks. Let’s use the %recall magic to get snippet [5], which created the rolls list, and place the code at the next In [] prompt:

```In [15]: %recall 5

In [16]: rolls = [random.randrange(1,   7) for i in range(600)]```

You can now edit the snippet to change the number of rolls to 60000, then press Enter to create a new list:

`In [16]: rolls = [random.randrange(1,   7) for i in range(60000)]`

Next, recall snippets [6] through [13]. This displays all the snippets in the specified range in the next In [] prompt. Press Enter to re-execute these snippets:

```In [17]: %recall 6-13

In [18]: values, frequencies = np.unique(rolls,   return_counts=True)
...: title = f'Rolling a Six-Sided   Die {len(rolls):,} Times'
...: sns.set_style('whitegrid')
...: axes = sns.barplot(x=values, y=frequencies,   palette='bright')
...: axes.set_title(title)
...: axes.set(xlabel='Die Value',   ylabel='Frequency')
...: axes.set_ylim(top=max(frequencies) * 1.10)
...: for bar, frequency in zip(axes.patches, frequencies):
...:     text_x = bar.get_x() + bar.get_width() / 2.0
...:     text_y = bar.get_height()
...:     text = f'{frequency:,}\n{frequency / len(rolls):.3%}'
...:     axes.text(text_x, text_y, text,
...:               fontsize=11,   ha='center', va='bottom')
...:              ```

The updated bar plot is shown below:

#### Saving Snippets to a File with the %save Magic

Once you’ve interactively created a plot, you may want to save the code to a file so you can turn it into a script and run it in the future. Let’s use the %save magic to save snippets 1 through 13 to a file named RollDie.py. IPython indicates the file to which the lines were written, then displays the lines that it saved:

```In [19]: %save RollDie.py 1-13
The following commands were written to file `RollDie.py`:
import matplotlib.pyplot as plt
import numpy as np
import random
import seaborn as sns
rolls = [random.randrange(1, 7) for i in range(600)]
values, frequencies = np.unique(rolls, return_counts=True)
title = f'Rolling a Six-Sided Die {len(rolls):,} Times'
sns.set_style("whitegrid")
axes = sns.barplot(values, frequencies, palette='bright')
axes.set_title(title)
axes.set(xlabel='Die Value', ylabel='Frequency')
axes.set_ylim(top=max(frequencies) * 1.10)
for bar, frequency in zip(axes.patches, frequencies):
text_x = bar.get_x() + bar.get_width() / 2.0
text_y = bar.get_height()
text = f'{frequency:,}\n{frequency / len(rolls):.3%}'
axes.text(text_x, text_y, text,
fontsize=11, ha='center', va='bottom')```

#### Command-Line Arguments; Displaying a Plot from a Script

Provided with this chapter’s examples is an edited version of the RollDie.py file you saved above. We added comments and a two modifications so you can run the script with an argument that specifies the number of die rolls, as in:

`     ipython RollDie.py 600`

The Python Standard Library’s sys module enables a script to receive command-line arguments that are passed into the program. These include the script’s name and any values that appear to the right of it when you execute the script. The sys module’s argv list contains the arguments. In the command above, argv[0] is the string 'RollDie.py' and argv[1] is the string '600'. To control the number of die rolls with the command-line argument’s value, we modified the statement that creates the rolls list as follows:

`     rolls = [random.randrange(1, 7) for i in range(int(sys.argv[1]))]`

Note that we converted the argv[1] string to an int.

Matplotlib and Seaborn do not automatically display the plot for you when you create it in a script. So at the end of the script we added the following call to Matplotlib’s show function, which displays the window containing the graph:

`     plt.show()`

### InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

## Overview

Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

## Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

### Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

### Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

### Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

### Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

### Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

### Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

## Other Collection and Use of Information

### Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

### Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

### Do Not Track

This site currently does not respond to Do Not Track signals.

## Security

Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

## Children

This site is not directed to children under the age of 13.

## Marketing

Pearson may send or direct marketing communications to users, provided that

• Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
• Such marketing is consistent with applicable law and Pearson's legal obligations.
• Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
• Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

## Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

## Choice/Opt-out

Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

## Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

## Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

## Sharing and Disclosure

Pearson may disclose personal information, as follows:

• As required by law.
• With the consent of the individual (or their parent, if the individual is a minor)
• In response to a subpoena, court order or legal process, to the extent permitted or required by law
• To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
• In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
• To investigate or address actual or suspected fraud or other illegal activities
• To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
• To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
• To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.