Skip to content

Latest commit

 

History

History
384 lines (267 loc) · 8.17 KB

cars-exploration.md

File metadata and controls

384 lines (267 loc) · 8.17 KB
jupyter
jupytext kernelspec plotly
notebook_metadata_filter text_representation
all
extension format_name format_version jupytext_version
.md
markdown
1.1
1.1.1
display_name language name
Python 3
python
python3
description display_as language layout name order permalink thumbnail
Use Plotly FigureWidget with hover callbacks and slider widgets
chart_events
python
base
Car Exploration with Hover Events
26
python/cars-exploration/
thumbnail/figurewidget-cars.gif

New to Plotly?

Plotly's Python library is free and open source! Get started by downloading the client and reading the primer.
You can set up Plotly to work in online or offline mode, or in jupyter notebooks.
We also have a quick-reference cheatsheet (new!) to help you get started!

Cars dataset exploration with plotly.py version 3.0

Load cars dataset

import pandas as pd
import numpy as np
import plotly.graph_objs as go

cars_df = pd.read_csv('data/cars/cars.csv',
                      usecols=['City mpg',
                               'Fuel Type',
                               'Horsepower',
                               'Model Year',
                               'Torque', 'Hybrid', 'ID'])
cars_df.sample(5)
cars_df.shape

Load images of cars

import os

image_data = {}
for img_filename in os.listdir('data/cars/images'):
    model_year = img_filename.split('.')[0]
    with open(f"data/cars/images/{img_filename}", "rb") as f:
        b = f.read()
        image_data[model_year] = b
from ipywidgets import Image
Image(value=image_data['2012_Chevrolet_Camaro_Coupe'])

Construct plotly.py Figure Widget

Torqe vs. MPG Scatter Trace

import plotly.graph_objs as go
fig = go.FigureWidget(
    data=[
        dict(
            type='scattergl',
            x=cars_df['Torque'],
            y=cars_df['City mpg'],
            mode='markers',
        )
    ],
)

Display Figure

Before online or offline iplot. Still supported, but not needed with FigureWidget

fig

Label Figure

Use property assignment syntax to:

Set fig.layout.title to 'Torque and Fuel Efficience'

fig.layout.title = 'Torque and Fuel Efficience'

Check default font size

fig.layout.titlefont.size

Increase the title font size

fig.layout.titlefont.size = 22

Set fig.layout.titlefont.family to 'Rockwell'

fig.layout.titlefont.family = 'Rockwell'

Create New View for Figure

If working in JupyterLab, right-click on blue bar to the left of the figure and select "Create New View for Output". Drag view to the right half of the screen.

Label Axes

Set the fig.layout.xaxis.title property to 'Torque (foot-pounds)'

fig.layout.xaxis.title = 'Torque (foot-pounds)'

Set the fig.layout.yaxis.title property to 'City MPG'

fig.layout.yaxis.title = 'City MPG'

Notice Quantization

Zoom in and notice that the dataset is quantized

Apply Jitter

scatter = fig.data[0]
scatter
N = len(cars_df)
scatter.x = scatter.x + np.random.rand(N) * 10
scatter.y = scatter.y + np.random.rand(N) * 1

Zoom level did not reset! Plot is updated in-place. Not recreated each time a property changes

Address Overplotting

Lower marker opacity

scatter.marker.opacity = 0.2

Decrease marker size

scatter.marker.size = 4

Aside on validation

What if I though opacity ranged from 0 to 255?

# scatter.marker.opacity = 50

What if I forgot the name of an enumeration value?

# fig.layout.hovermode = 'nearest' # Set to 'closest'
fig.layout.hovermode = 'closest'

What if I don't know how to spell 'fuchsia'?

scatter.marker.color = 'fuchsia' # Set to 'fuchsia'

Restore default marker color

scatter.marker.color = None

Add density contour

Add smoothed density contour trace (histogram2dcontour) based on scatter.x and y=scatter.y values.

contour = fig.add_histogram2dcontour(
    x=scatter.x, y=scatter.y)

Set contour colorscale

contour.colorscale = 'Hot'

Reverse the colorscale

contour.reversescale = True

Disable tooltips for contour

contour.hoverinfo = 'skip'

Tweak marker size and opacity

scatter.marker.opacity = .1
scatter.marker.size = 3

Create marker configuration widget

Define function that inputs opacity and size and updates the figure.

def set_opacity(opacity, size):
    scatter.marker.opacity = opacity
    scatter.marker.size = size

Use ipywidgets.interactive to generate control panel for function.

from ipywidgets import interactive
opacity_slider = interactive(set_opacity,
                             opacity=(0.0, 1.0, 0.01),
                             size=(1, 10, 0.25))
opacity_slider

Adjust the width of the slider widgets

opacity_slider.children[0].layout.width = '400px'
opacity_slider.children[1].layout.width = '400px'

Try zooming and then adjusting the marker params

Looking at outliers

Tooltips

Use 'ID' column as tooltip for scatter

scatter.text = cars_df['ID']
scatter.hoverinfo = 'text'

All properties

Create an HTML widget to display the hover properties

from ipywidgets import HTML
details = HTML()
details

Register callback function to be executed on hover events. It will update the HTML widget using the pandas to_html method.

def hover_fn(trace, points, state):
    ind = points.point_inds[0]
    details.value = cars_df.iloc[ind].to_frame().to_html()

scatter.on_hover(hover_fn)

Vehicle image

Create an ipywidgets.Image widget to display images

from ipywidgets import Image, Layout
image_widget = Image(
    value=image_data['2012_Chevrolet_Camaro_Coupe'],
    layout=Layout(height='252px', width='400px')
)
image_widget

Update hover function to update the image widget along with the HTML widget

def hover_fn(trace, points, state):

    ind = points.point_inds[0]

    # Update details HTML widget
    details.value = cars_df.iloc[ind].to_frame().to_html()

    # Update image widget
    model_year = cars_df['Model Year'][ind].replace(' ', '_')
    image_widget.value = image_data[model_year]

scatter.on_hover(hover_fn)

Bringing it all together

Create simple dashboard using HBox and VBox containers

from ipywidgets import HBox, VBox
VBox([fig,
      opacity_slider,
      HBox([image_widget, details])])

Reference

See these Jupyter notebooks for even more FigureWidget examples.

help(go.FigureWidget)
from IPython.display import display, HTML

display(HTML('<link href="//fonts.googleapis.com/css?family=Open+Sans:600,400,300,200|Inconsolata|Ubuntu+Mono:400,700" rel="stylesheet" type="text/css" />'))
display(HTML('<link rel="stylesheet" type="text/css" href="http://help.plot.ly/documentation/all_static/css/ipython-notebook-custom.css">'))

! pip install git+https://github.com/plotly/publisher.git --upgrade

import publisher
publisher.publish(
    'cars-exploration.ipynb', 'python/cars-exploration/', 'Car Exploration with go.FigureWidget, Case Study',
    'Use Plotly FigureWidget with hover callbacks and slider widgets',
    title = 'Car Exploration with Hover Events',
    name = 'Car Exploration with Hover Events',
    has_thumbnail='true', thumbnail='thumbnail/zoom.jpg',
    language='python', page_type='example_index',
    display_as='chart_events', order=26,
    ipynb= '~notebook_demo/242')