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 confidence interval -- the range of the number of votes which encapsulates 95% of the data (see the boxplot lectures for more information, and the yerr parameter of barcharts).


        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 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).



In [1]:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import matplotlib.cm as colormap
from matplotlib.widgets import SpanSelector

%matplotlib notebook

In [2]:
np.random.seed(12345)

df = pd.DataFrame([np.random.normal(33500,150000,3650), 
                   np.random.normal(41000,90000,3650), 
                   np.random.normal(41000,120000,3650), 
                   np.random.normal(48000,55000,3650)], 
                  index=[1992,1993,1994,1995])

In [3]:
x_val = np.arange(len(df.index))
df["mean"] = df.apply(lambda x:x.mean(), axis=1)
df["std"] = df.apply(lambda x:x.std(), axis=1)
values = df["mean"]

sample_size = 3650
df["confidence"] = df.apply(lambda x: 1.96 * (x[3651] / np.sqrt(sample_size)), axis=1)
df["upper_confidence"] = df.apply(lambda x: x[3650] + x[3652], axis=1)
df["lower_confidence"] = df.apply(lambda x: x[3650] - x[3652], axis=1)

In [ ]:
_ = plt.figure()

range_value = int(input("Enter y axis value : "))
lower_values = df["lower_confidence"]
upper_values = df["upper_confidence"]

color_values = []
for val in zip(upper_values, lower_values):
    if range_value >= val[1] and range_value <= val[0]:
        color_values.append("w")
    elif range_value < val[1]:
        color_values.append("r")
    elif range_value > val[0]:
        color_values.append("b")

_ = plt.bar(x_val, values, color=color_values, align='center', alpha=0.8, yerr=df["confidence"], edgecolor="black")
_ = plt.xticks(x_val, df.index)
_ = plt.axhline(y=range_value, linewidth=1, color="black")

In [ ]:
_ = plt.figure()

range_value = int(input("Enter y axis value : "))
lower_value = df["lower_confidence"]
upper_value = df["upper_confidence"]

normalize_values = [colors.Normalize(vmin=val[0], vmax=val[1], clip=True) for val in zip(lower_value, upper_value)]
cmap = colormap.get_cmap("bwr")
sm = plt.cm.ScalarMappable(cmap=cmap)
sm.set_array([])
color_val = [cmap(1 - x(range_value)) for x in normalize_values]

_ = plt.bar(x_val, values, color=color_val, alpha=0.8, align='center', yerr=df["confidence"], edgecolor="black")
_ = plt.xticks(x_val, df.index)
_ = plt.axhline(y=range_value, linewidth=0.5, color="black")
_ = plt.colorbar(sm, alpha=0.8, orientation="vertical")

In [90]:
_ = plt.figure()

range_value = 0
lower_value = df["lower_confidence"]
upper_value = df["upper_confidence"]

normalize_values = [colors.Normalize(vmin=val[0], vmax=val[1], clip=True) for val in zip(lower_value, upper_value)]
cmap = colormap.get_cmap("bwr")
sm = plt.cm.ScalarMappable(cmap=cmap)
sm.set_array([])
color_val = []

def repeat_draw():
    global color_val
    _ = plt.bar(x_val, values, color=color_val, alpha=0.6, align='center', linewidth=0.5, yerr=df["confidence"], edgecolor="black")
    _ = plt.xticks(x_val, df.index, alpha=0.7)
    _ = plt.yticks(alpha=0.7)
    
    for spine in zip(plt.gca().spines, plt.gca().spines.values()):
        if spine[0] == "top" or spine[0] == "right":
            spine[1].set_visible(False)
        else:
            spine[1].set_alpha(0.2)

def on_press(event):
    global color_val
    plt.cla()
    range_value = event.ydata
    color_val = [cmap(1 - x(range_value)) for x in normalize_values]
    repeat_draw()
    _ = plt.gca().set_title("Value of y axis selected : " + str(range_value), fontsize=10, alpha=0.7)
    _ = plt.axhline(y=range_value, linewidth=0.5, color="black")
    
repeat_draw()
clrbar = plt.colorbar(sm, alpha=0.6, orientation="vertical", drawedges=False)
        
_ = plt.gcf().canvas.mpl_connect('button_press_event', on_press)



In [77]:
_ = plt.figure()

range_value = 0
lower_value = df["lower_confidence"]
upper_value = df["upper_confidence"]

normalize_values = [colors.Normalize(vmin=0, vmax=val[1]) for val in zip(lower_value, upper_value)]
cmap = colormap.get_cmap("bwr")
sm = plt.cm.ScalarMappable(cmap=cmap)
sm.set_array([])
ax = plt.gca()

_ = plt.bar(x_val, values, color=color_val, alpha=0.4, align='center', yerr=df["confidence"], edgecolor="black")
_ = plt.xticks(x_val, df.index)
_ = plt.colorbar(sm, alpha=0.6, orientation="vertical")

def onselect(ymin, ymax):
    plt.cla()
    color_val = [cmap(1 - x(range_value)) for x in normalize_values]
    _ = plt.bar(x_val, values, color=color_val, alpha=0.6, align='center', yerr=df["confidence"], edgecolor="black")
    _ = plt.xticks(x_val, df.index)
    
span = SpanSelector(ax=ax, onselect=onselect, direction="vertical", useblit=True, 
                    rectprops=dict(alpha=0.3, facecolor='red'))


  File "<ipython-input-77-ce5320d2c799>", line 7
    normalize_values = [colors.Normalize(vmin=, vmax=val[1]) for val in zip(lower_value, upper_value)]
                                              ^
SyntaxError: invalid syntax

In [ ]: