# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 2
#     language: python
#     name: python2
# ---

# # Visualization in Depth With Bokeh

# For details on bokeh, see http://bokeh.pydata.org/en/latest/docs/user_guide.html#userguide

# ## Setup

from bokeh.plotting import figure, output_file, show, output_notebook, vplot
import random
import numpy as np
import pandas as pd
output_notebook()  # Use so see output in the Jupyter notebook

import bokeh
bokeh.__version__

# ## Objectives

# - Describe how to create interactive visualizations using bokeh
#  - Running example and visualization goals
#  - How to approach a new system
#  - Hover
#  - Widgets
# - Study bokeh as a system
#  - Function specification - what it provides programmers
#  - Design (which has client and server parts)

# ## How to Learn a New System

# Steps
# - Find an example close to what you want
# - Create an environment that runs the example
# - Abstract the key concepts of how it works
# - Transform the example into what you want

# ## Running Example - Biological Data

from IPython.display import Image
Image(filename='biological_data.png') 

df_bio = pd.read_csv("biological_data.csv")
df_bio.head()

# Desired visualization
# - Scatterplot of rate vs. yield
# - Hover shows the evolutionary "line"
# - Widgets can specify color (and legend) for values of line

# ## Step 1: Find something close

plot = figure(plot_width=400, plot_height=400)
plot.circle(df_bio['rate'], df_bio['yield'])
plot.xaxis.axis_label = 'rate'
plot.yaxis.axis_label = 'yield'
show(plot)

# ### Step 1a: Distinguish "evolutionary lines" by color

# Let's distinguish the lines with colors. First, how many lines are there?

# What are the possible colors
df_bio['line'].unique()

# Generate a plot with a different color for each line
colors = {'HA': 'red', 'HR': 'green', 'UA': 'blue', 'WT': 'purple'}
plot = figure(plot_width=700, plot_height=800)
plot.title.text = 'Phenotypes for evolutionary lines.'
for line in list(colors.keys()):
    df = df_bio[df_bio.line == line]
    color = colors[line]
    plot.circle(df['rate'], df['yield'], color=color, legend=line)
plot.legend.location = "top_right"
show(plot)

# What colors are possible to use? Check out bokeh.palettes

import bokeh.palettes as palettes
print palettes.__doc__
#palettes.magma(4)

# **Exercise**: Handle colors for the plot for an arbitrary number of evolutionary lines. (Hint: construct the colors dictionary using the values of 'line' and a palette.)

# +
# Generate the colors dictionary
# Fill this in....

# +
# Plot with the generated palette
# Fill this in ...
# -

# ### Bokeh tools

# Tools can be specified and positioned when the Figure is created. The interaction workflow is (a) select a tool (identified by vertical blue line), (b) perform gesture for tool.

TOOLS = 'box_zoom,box_select,resize,reset'
plot = figure(plot_width=200, plot_height=200, title=None, tools=TOOLS)
plot.scatter(range(10), range(10))
show(plot)

from bokeh.models import HoverTool, BoxSelectTool
TOOLS = [HoverTool(), BoxSelectTool()]
plot = figure(plot_width=200, plot_height=200, title=None, tools=TOOLS)
show(plot)

# ### Synthesizing Bokeh Concepts (Classes)

# **Figure**
# - Created using the figure()
# - Controls the size of the plot
# - Allows other elements to be added
# - Has properties for title, x-axis label, y-axis label
#
# **Glyph**
# - Mark that's added to the plot - circle, line, polygon
# - Created using Figure methods plot.circle(df['rate'], df['yield'], color=color, legend=line)
#
# **Tool**
# - Provides user interactions with the graph using gestures
# - Created using a separate constructor (
#

# ### Adding a Hover Tool

# Based on our knowledge of Bokeh concepts, is a Tool associated with Figure or Glyph?

# Which classes will be involved in hovering:
# - Plot & Tool only
# - Glyph only
# - Tool and Glyph

# Start with some examples. First, simple hovering.

# +
from bokeh.plotting import figure, output_file, show
from bokeh.models import HoverTool, BoxSelectTool

output_file("toolbar.html")
TOOLS = [BoxSelectTool(), HoverTool()]

p = figure(plot_width=400, plot_height=400, title=None, tools=TOOLS)

p.circle([1, 2, 3, 4, 5], [2, 5, 8, 2, 7], size=10)

show(p)
# -

# Now add ad-hoc data

# +
from bokeh.plotting import figure, output_file, show, ColumnDataSource
from bokeh.models import HoverTool

output_file("toolbar.html")



hover = HoverTool(
        tooltips=[
            ("index", "$index"),
            ("(x,y)", "(@x, @y)"),
            ("desc", "@desc"),
        ]
    )

p = figure(plot_width=400, plot_height=400, tools=[hover],
           title="Mouse over the dots")


source = ColumnDataSource(
        data={
            'x': [1, 2, 3, 4, 5],
            'y': [2, 5, 8, 2, 7],
            'desc': ['A', 'b', 'C', 'd', 'E'],
        }
    )


p.circle('x', 'y', size=20, source=source)

show(p)
# -

# **Exercise**: Plot the biological data with colors and a hover that shows the evolutionary line.

# ## Bokeh Widgets

# See widget.py and my_app.py

# ## Bokeh Server

Image(filename='BokehArchitecture.png') 

StarcoderdataJupyterScriptsDedupFiltered