Basic Data Visualization

np.linspace(0, 100, 11)

creates a list of values from 0 to 100 with 11 elements. In other words (0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100). See the linspace documentation.

Matplotlib is one of the most common plotting packages in Python to use it more succinctly

from matplotlib import pyplot as plt
# This line is needed
%matplotlib inline

def visualize_one_die(roll_data):
    """
    Visualizes the dice rolls
    
    Args:
        roll_data (int): roll counts in a list from [1,6]
        
    Returns:
        None - shows a plot with the x-axis is the dice values
               and the y-axis as the frequency for t
    """
    roll_outcomes = [1,2,3,4,5,6]
    fig, ax = plt.subplots()
    ax.bar(roll_outcomes, roll_data)
    ax.set_xlabel("Value on Die")
    ax.set_ylabel("# rolls")
    ax.set_title("Simulated Counts of Rolls")
    plt.show()
    
roll_data = simulate_dice_rolls(500)
visualize_one_die(roll_data)

Example: ScatterPlot

We are using some made-up data for the x and y positons of the points.

import matplotlib.pyplot as plt
%matplotlib inline

x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

plt.scatter(x, y)
plt.xlabel('x values')
plt.ylabel('y values')
plt.title('X values versus Y values')
plt.xticks([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
plt.show()

Example: Bar Chart

import matplotlib.pyplot as plt
%matplotlib inline

x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

plt.bar(x, y)
plt.xlabel('x values')
plt.ylabel('y values')
plt.title('X values versus Y values')
plt.xticks([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
plt.show()

Example: Bar Chart Again

You might remember that the x-axis is actually a discrete variable. The major change in the code was that the x values are now strings instead of numerical.

import matplotlib.pyplot as plt
%matplotlib inline

x = ['apples', 'pears', 'bananas', 
     'grapes', 'melons', 'avocados', 'cherries', 'oranges', 'pumpkins',
    'tomatoes']
y = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

plt.bar(x, y)
plt.xlabel('x values')
plt.ylabel('y values')
plt.title('X values versus Y values')
plt.xticks(rotation=70)
plt.show()

Last updated