Assignment 3 - Building a Custom Visualization


In this assignment you must choose one of the options presented below and submit a visual as well as your source code for peer grading. The details of how you solve the assignment are up to you, although your assignment must use matplotlib so that your peers can evaluate your work. The options differ in challenge level, but there are no grades associated with the challenge level you chose. However, your peers will be asked to ensure you at least met a minimum quality for a given technique in order to pass. Implement the technique fully (or exceed it!) and you should be able to earn full grades for the assignment.

      Ferreira, N., Fisher, D., & Konig, A. C. (2014, April). Sample-oriented task-driven visualizations: allowing users to make better, more confident decisions.       In Proceedings of the SIGCHI Conference on Human Factors in Computing Systems (pp. 571-580). ACM. (video)

In this paper the authors describe the challenges users face when trying to make judgements about probabilistic data generated through samples. As an example, they look at a bar chart of four years of data (replicated below in Figure 1). Each year has a y-axis value, which is derived from a sample of a larger dataset. For instance, the first value might be the number votes in a given district or riding for 1992, with the average being around 33,000. On top of this is plotted the 95% confidence interval for the mean (see the boxplot lectures for more information, and the yerr parameter of barcharts).


Figure 1

        Figure 1 from (Ferreira et al, 2014).


A challenge that users face is that, for a given y-axis value (e.g. 42,000), it is difficult to know which x-axis values are most likely to be representative, because the confidence levels overlap and their distributions are different (the lengths of the confidence interval bars are unequal). One of the solutions the authors propose for this problem (Figure 2c) is to allow users to indicate the y-axis value of interest (e.g. 42,000) and then draw a horizontal line and color bars based on this value. So bars might be colored red if they are definitely above this value (given the confidence interval), blue if they are definitely below this value, or white if they contain this value.


Figure 1

Figure 2c from (Ferreira et al. 2014). Note that the colorbar legend at the bottom as well as the arrows are not required in the assignment descriptions below.



Figure 2c from (Ferreira et al. 2014). Note that the colorbar legend at the bottom as well as the arrows are not required in the assignment descriptions below.

Easiest option: Implement the bar coloring as described above - a color scale with only three colors, (e.g. blue, white, and red). Assume the user provides the y axis value of interest as a parameter or variable.

Harder option: Implement the bar coloring as described in the paper, where the color of the bar is actually based on the amount of data covered (e.g. a gradient ranging from dark blue for the distribution being certainly below this y-axis, to white if the value is certainly contained, to dark red if the value is certainly not contained as the distribution is above the axis).

Even Harder option: Add interactivity to the above, which allows the user to click on the y axis to set the value of interest. The bar colors should change with respect to what value the user has selected.

Hardest option: Allow the user to interactively set a range of y values they are interested in, and recolor based on this (e.g. a y-axis band, see the paper for more details).


Note: The data given for this assignment is not the same as the data used in the article and as a result the visualizations may look a little different.

In [1]:
%%capture
%matplotlib notebook

import matplotlib as mpl
from matplotlib.animation import FuncAnimation as FA
import matplotlib.colorbar as cb
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import statistics as st

###Use the following data for this assignment:
np.random.seed(12345)

df = pd.DataFrame([np.random.normal(32000,200000,3650), 
                   np.random.normal(43000,100000,3650), 
                   np.random.normal(43500,140000,3650), 
                   np.random.normal(48000,70000,3650)],
                  index=[1992,1993,1994,1995]
                 )


#Helper function to return mean and error from a list.
def conf_int(data):
    mean = st.mean(data)
    std = st.stdev(data)
    error = 1.96 * std / ((len(data)) ** 0.5)
    return mean, error

#Helper function.  Given a hval, the function will calculate where the value
#lies relative to the mean and error of a dataset.  If it is less, it will be 
#darker blue to lighter blue, equal is white, and greater is lighter red to 
#darker red.  This color is appended to a list.  The list of all colors is
#returned.
def bar_colors(hval, yvals, yerr) :
    bar_color = []
    for y in range(len(yvals)) :
        bar_color.append(mpl.cm.RdBu_r((yvals[y] - hval) / (2 * yerr[y]) + .5))
    return bar_color  

#Animate function.  Sets up primary bar plot.  Updates the color of the bars
#and the horizontal line with each iteration.
def animate(i) :
    ax1.cla()
    ax1.set_xticks(xvals)
    ax1.bar(xvals, yvals,
            width = 1, yerr = yerr,
            capsize = 15,
            color = bar_colors(hval[i], yvals, yerr), 
            edgecolor = 'black'
            )
    ax1.axhline(hval[i],
                color = 'grey',
                linestyle = '-',
                linewidth = 2)

#Retrieve mean and error for each year.
conf_int_1992 = conf_int(df.loc[1992])
conf_int_1993 = conf_int(df.loc[1993])
conf_int_1994 = conf_int(df.loc[1994])
conf_int_1995 = conf_int(df.loc[1995])

#Domain is the four years.
xvals = df.index.values
#Range is the means of each of the four years.
yvals = [conf_int_1992[0], conf_int_1993[0], conf_int_1994[0], conf_int_1995[0]]
#Errors of each of the four years.
yerr = [conf_int_1992[1], conf_int_1993[1], conf_int_1994[1], conf_int_1995[1]]

#Array of random relevant horizontal lines to draw.
n = 50
hval = np.random.randint(25000,50000,n)

#Two plots - the main bar chart and the colorbar.    
f, (ax1, ax2) = plt.subplots(2, gridspec_kw = {'height_ratios': [10, .5]})

#Colorbar legend remains unchanged throughout animation. 
cb.ColorbarBase(ax2,
                cmap = mpl.cm.get_cmap('RdBu_r', 11),
                norm = mpl.colors.Normalize(vmin = 0, vmax = 1),
                orientation = 'horizontal'
                )

#Run animation.  
anim = FA(f, animate, frames = 50, interval = 500, blit = True)
plt.close(anim._fig)
In [2]:
#Save animation.
anim.save("bars.mp4", writer='ffmpeg');

from IPython.display import Video

Video("bars.mp4")
Out[2]: