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

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]:
# Use the following data for this assignment:

#%matplotlib inline

import pandas as pd
import numpy as np
import math

np.random.seed(12345)

# mean, std, size

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

sqr_n = math.sqrt(3650)

df = df.transpose()

df_stat = df.describe()

df_means = df_stat.loc["mean"]
df_errors = df_stat.loc["std"]
df_SEM = df_errors/sqr_n

year_labels = df_means.index
numpy_years = year_labels.to_numpy()
numpy_SEM = df_SEM.to_numpy()
numpy_data = df_means.to_numpy()


In [2]:
# light blue if below
# white if inside
# red if above

def pick_colors(numpy_years, numpy_SEM, numpy_data, y_value ):

colors = []
for item in range(0,len(numpy_SEM)):
#print(numpy_years[item], numpy_SEM[item], numpy_data[item])
#print('range: ', numpy_data[item]-numpy_SEM[item], '-',numpy_data[item]+numpy_SEM[item], y_value ,'\n')
if y_value < (numpy_data[item]-numpy_SEM[item]):
#print('firing blue: ', numpy_data[item]-numpy_SEM[item],'>',y_value)
color = 'tomato'
elif numpy_data[item]-numpy_SEM[item] < y_value and y_value < numpy_data[item]+numpy_SEM[item]:
color = 'white'
#print('firing white')
else:
color = 'red'
#print('firing red')

#print(color)
colors.append(color)
#print()
return colors

#y_value = 40234
#print(pick_colors(numpy_years, numpy_SEM, numpy_data, y_value ))

In [3]:
import logging
logging.basicConfig(format='%(asctime)s  %(funcName)s %(lineno)d: %(message)s',
datefmt='%m/%d/%Y %I:%M:%S %p',
filename='aa-logs.log',
filemode='w',
level=logging.CRITICAL)

In [4]:
%matplotlib notebook
import matplotlib.pyplot as plt
from matplotlib.widgets import TextBox
import matplotlib.lines as lines
from matplotlib.ticker import (MultipleLocator, FormatStrFormatter,
AutoMinorLocator,LogFormatterSciNotation )

y_init = 30000
colors = pick_colors(numpy_years, numpy_SEM, numpy_data, y_init )

# return the figure and axes
fig, ax = plt.subplots()

## do the bar chart
edgecolors = ['black','black','black','black']
bar_chart = ax.bar(x=numpy_years,
height=numpy_data,
yerr=numpy_SEM,
color=colors,
width=1.0,
edgecolor=edgecolors)

# reduce the number of xticks
xticks = ax.get_xticks()
xticks = xticks[0::2]
ax.set_xticks(xticks)

ax.set_ylim([0,50000])

## do the line
x = [1991, 1996]
y = [y_init, y_init]
line, = ax.plot(x,y, 'r--', label='y value')
plt.title('Bars colored red if they are definitely above given value;\n\
blue if they are definitely below given value; \n\
white if they contain given value.')

def submit(text):
logging.info(text)
ydata = eval(text)
colors = pick_colors(numpy_years, numpy_SEM, numpy_data, ydata )
logging.info(colors)
line.set_ydata(ydata)

counter = 0
for bar in bar_chart:
logging.info(' Patch number: {}'.format(counter) )
bar.set_color(colors[counter])
bar.set_edgecolor('black')
counter = counter + 1
ax.relim()
ax.autoscale_view()
_ = plt.draw()

# do the text box
axbox = fig.add_axes([0.1, 0.05, 0.8, 0.075])
label = 'Enter y-value:'
text_box = TextBox(axbox, label, initial=y_init)
text_box.on_submit(submit)
# could not get textbox to be interactive with out this call.
text_box.set_val(y_init)


In [ ]:

In [ ]:

In [ ]: