Profile picture

Data Scientist @ RMOTR

Interactive Chartify Tutorial

Last updated: October 9th, 20192019-10-09Project preview
In [1]:
from bokeh.plotting import figure, output_file, show
from bokeh.io import output_notebook

output_notebook()
Loading BokehJS ...
In [56]:
# Copyright (c) 2017-2018 Spotify AB
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import chartify
import pandas as pd

def print_public_methods(obj):
    print('Methods:')
    print('\n'.join([x for x in dir(obj) if not x.startswith('_')]))

Chart object

  • Run the cell below to instantiate a chart and assign to to a variable
In [2]:
ch = chartify.Chart()
ch
Out[2]:
chartify.Chart(blank_labels=False,
layout='slide_100%',
x_axis_type='linear',
y_axis_type='linear')
  • Use .show() to render the chart.
In [3]:
ch.show()
  • Note that the chart is blank at this point.
  • The default labels provide directions for how to override their values.

Adding chart labels

  • Your turn: Add labels to the following chart. Look at the default values for instruction.
  • Title
  • Subtitle
  • Source
  • X label
  • Y label
In [4]:
ch = chartify.Chart()

# set title
ch.set_title('My Title')

# set subtitle
ch.set_subtitle('Data description')

# set source
ch.set_source_label('Source')

# set X label
ch.axes.set_xaxis_label('X label')

# set Y label
ch.axes.set_yaxis_label('Y label')

ch.show()

Getting help

  • From within a jupyter notebook you can see the available attributes of the chart object by pressing "tab"
  • Select the space just after the "." character below and hit tab.
In [ ]:
ch = chartify.Chart()
ch.
  • You can also use "?" to pull up documentation for objects and methods.
  • Run the cell below to pull up the chartify.Chart documentation
In [6]:
chartify.Chart?
Init signature: chartify.Chart(blank_labels=False, layout='slide_100%', x_axis_type='linear', y_axis_type='linear')
Docstring:     
Class Docstring

- Styling (.style)
- Plotting (.plot)
- Callouts (.callout)
- Axes (.axes)
- Bokeh figure (.figure)
Init docstring:
Create a chart instance.

Args:
    blank_labels (bool): When true removes the title,
        subtitle, axes, and source labels from the chart.
        Default False.
    layout (str): Change size & aspect ratio of the chart for
        fitting into slides.
        - 'slide_100%'
        - 'slide_75%'
        - 'slide_50%'
        - 'slide_25%'
    x_axis_type (enum, str): Type of data plotted on the X-axis.
        - 'linear':
        - 'log':
        - 'datetime': Use for datetime formatted data.
        - 'categorical':
        - 'density'

    y_axis_type (enum, str): Type of data plotted on the Y-axis.
        - 'linear':
        - 'log':
        - 'categorical':
        - 'density'
Note:
    Combination of x_axis_type and y_axis_type will determine the
    plotting methods available.
File:           /usr/local/lib/python3.6/site-packages/chartify/_core/chart.py
Type:           type
  • This can also be accomplished by pressing "shift + tab".
  • Press "shift + tab" twice to see the expanded documentation.
  • Try it with the next cell.
In [7]:
chartify.Chart
Out[7]:
chartify._core.chart.Chart

Callouts

  • The chart object has a callout object (ch.callout) that contains methods for adding callouts to the chart.
  • Callouts can be used to add text, lines, or shaded areas to annotate parts of your chart.
  • Look up the documentation for ch.callout.text if you need help
In [8]:
ch.callout.text?
Signature: ch.callout.text(text, x, y, text_color='black', text_align='left', font_size='1em', angle=0)
Docstring:
Add text callout to the chart.

        Note:
            Use `
` within text for newlines.
        Args:
            x (numeric): x location of the text.
            y (numeric, optional): y location of the text.
            text_color (str): Color name or hex value.
                See chartify.color_palettes.show() for available color names.
            text_align (str: 'left', 'right', 'center'): Text alignment.
            font_size (str): Font size.
            angle (int, 0 to 360): Angle in degrees from horizontal. Default: 0

        Returns:
            Current chart object
        
File:      /usr/local/lib/python3.6/site-packages/chartify/_core/callout.py
Type:      method
  • Your Turn: Fill in the code below to add a text callout that says "Hi" at coordinate (10, 10)
In [9]:
ch = chartify.Chart()

ch.set_title('My Title')
ch.set_subtitle('Data description')
ch.set_source_label('Source')
ch.axes.set_xaxis_label('X label')
ch.axes.set_yaxis_label('Y label')

# Add your code here to add a text callout
ch.callout.text('Hi', 10, 10, text_color='#3390FF', font_size='2em')
    
ch.show()
  • Use tab below to see what callouts are available.
In [ ]:
ch.callout.
  • You should see this list of callouts:
In [11]:
# List of available callouts:
print_public_methods(ch.callout)
Methods:
box
line
line_segment
text

Axes

  • The axes object contains methods for setting or getting axis properties.
In [12]:
# Avaiable axes methods:
print_public_methods(ch.axes)
Methods:
hide_xaxis
hide_yaxis
set_xaxis_label
set_xaxis_range
set_xaxis_tick_format
set_xaxis_tick_orientation
set_xaxis_tick_values
set_yaxis_label
set_yaxis_range
set_yaxis_tick_format
set_yaxis_tick_values
xaxis_label
yaxis_label
  • Your turn: modify the chart below so the xaxis range goes from 0 to 100
In [13]:
ch = chartify.Chart()

ch.set_title('My Title')
ch.set_subtitle('Data description')
ch.set_source_label('Source')
ch.axes.set_xaxis_label('X label')
ch.axes.set_yaxis_label('Y label')

ch.callout.text('Hi', 10, 10, text_color='#3390FF', font_size='2em')

# Add code here to modify the xrange to (0, 100)
ch.axes.set_xaxis_range(0, 100)

ch.show()

Method chaining

  • Chart methods can be chained by wrapping the statments in parentheses. See the example below:
In [14]:
(chartify.Chart(blank_labels=True)
 .callout.text('Hi', 10, 10, text_color='#3390FF', font_size='2em')
 .axes.set_xaxis_range(0, 100) 
 .show()
)

Plotting

Input data format

Chartify expects the input data to be:

  • Tidy (Each variable has its own column, each row corresponds to an observation)
  • In the columns of a Pandas DataFrame.

Below we'll explore some examples of valid and invalid input data

  • Run this cell to generate an example dataset
In [15]:
data = chartify.examples.example_data()
data.head()
Out[15]:
date country fruit unit_price quantity total_price
0 2017-10-21 US Banana 0.303711 4 1.214846
1 2017-05-30 JP Banana 0.254109 4 1.016436
2 2017-05-21 CA Banana 0.268635 4 1.074539
3 2017-09-18 BR Grape 2.215277 2 4.430554
4 2017-12-08 US Banana 0.308337 5 1.541687

Pivoted data: INVALID

  • Pivoted data is not Tidy (note the country dimension has an observation in each column)
In [16]:
pivoted_data = pd.pivot_table(data, columns='country', values='quantity', index='fruit', aggfunc='sum')
pivoted_data
Out[16]:
country BR CA GB JP US
fruit
Apple 57 144 177 65 165
Banana 30 222 113 232 479
Grape 54 86 59 52 81
Orange 74 207 97 75 409

Melting pivoted data: VALID

  • You can use pandas.melt to convert pivoted data into the tidy data format.
  • The output of SQL queries with groupby produces output in tidy format.
In [17]:
value_columns = pivoted_data.columns

melted_data = pd.melt(pivoted_data.reset_index(), # Need to reset the index to put "fruit" into a column.
                      id_vars='fruit',
                      value_vars=value_columns)
melted_data.head()
Out[17]:
fruit country value
0 Apple BR 57
1 Banana BR 30
2 Grape BR 54
3 Orange BR 74
4 Apple CA 144

Pandas series: INVALID

  • Data in a pandas Series must be converted to a DataFrame for use with Chartify.
In [18]:
data.groupby(['country'])['quantity'].sum()
Out[18]:
country
BR     215
CA     659
GB     446
JP     424
US    1134
Name: quantity, dtype: int64

Pandas index: INVALID

  • The output below is a pandas DataFrame, but the country dimension is in the Index.
In [19]:
data.groupby(['country'])[['quantity']].sum()
Out[19]:
quantity
country
BR 215
CA 659
GB 446
JP 424
US 1134

Pandas DataFrame: VALID

  • The code below produces a valid pandas DataFrame for use with Chartify.
  • Notice how the country dimension is now in a column.
In [20]:
chart_data = data.groupby(['country'])['quantity'].sum().reset_index()
chart_data
Out[20]:
country quantity
0 BR 215
1 CA 659
2 GB 446
3 JP 424
4 US 1134

Axis types

  • Specify the x_axis_type and y_axis_type parameters when instantiating the chart object.
  • Both are set to linear by default.
  • Look at the chart object documentation to see the list of available options for x_axis_type and y_axis_type
In [21]:
chartify.Chart?
Init signature: chartify.Chart(blank_labels=False, layout='slide_100%', x_axis_type='linear', y_axis_type='linear')
Docstring:     
Class Docstring

- Styling (.style)
- Plotting (.plot)
- Callouts (.callout)
- Axes (.axes)
- Bokeh figure (.figure)
Init docstring:
Create a chart instance.

Args:
    blank_labels (bool): When true removes the title,
        subtitle, axes, and source labels from the chart.
        Default False.
    layout (str): Change size & aspect ratio of the chart for
        fitting into slides.
        - 'slide_100%'
        - 'slide_75%'
        - 'slide_50%'
        - 'slide_25%'
    x_axis_type (enum, str): Type of data plotted on the X-axis.
        - 'linear':
        - 'log':
        - 'datetime': Use for datetime formatted data.
        - 'categorical':
        - 'density'

    y_axis_type (enum, str): Type of data plotted on the Y-axis.
        - 'linear':
        - 'log':
        - 'categorical':
        - 'density'
Note:
    Combination of x_axis_type and y_axis_type will determine the
    plotting methods available.
File:           /usr/local/lib/python3.6/site-packages/chartify/_core/chart.py
Type:           type
  • The Chart axis types influence the plots that are available
  • Look at how the plot methods change based on the axis types:
In [22]:
ch = chartify.Chart(x_axis_type='datetime',
                    y_axis_type='linear')

# List of available callouts:
print_public_methods(ch.plot)
Methods:
area
line
scatter
text
In [23]:
ch = chartify.Chart(x_axis_type='categorical',
                    y_axis_type='linear')

# List of available plots:
print_public_methods(ch.plot)
Methods:
bar
bar_stacked
interval
lollipop
parallel
scatter
text
text_stacked
  • Your turn: Create a chart with 'density' y and 'linear' x axis types. What type of plots are available?
In [24]:
ch = chartify.Chart(# Your code goes here
                    x_axis_type='linear',
                    y_axis_type='density')

print_public_methods(ch.plot)
Methods:
histogram
kde

Vertical Bar plot

  • Your turn: Create a bar plot based on the dataframe below.
In [25]:
bar_data = (data.groupby('country')[['quantity']].sum()
            .reset_index()
           )
bar_data
Out[25]:
country quantity
0 BR 215
1 CA 659
2 GB 446
3 JP 424
4 US 1134
  • Your turn: Implement the bar plot here.
  • Set the appropriate x_axis_type otherwise the bar method won't be available.
  • Look at the bar documentation to figure out how to pass in the parameters.
  • If you get stuck move on to the next section for hints.
In [26]:
ch = chartify.Chart(# Your code goes here
                    x_axis_type='categorical',
                    y_axis_type='linear')

ch.plot.bar?
Signature: ch.plot.bar(data_frame, categorical_columns, numeric_column, color_column=None, color_order=None, categorical_order_by='values', categorical_order_ascending=False)
Docstring:
Bar chart.

Note:
    To change the orientation set x_axis_type or y_axis_type
    argument of the Chart object.

Args:
    data_frame (pandas.DataFrame): Data source for the plot.
    categorical_columns (str or list): Column name to plot on
        the categorical axis.
    numeric_column (str): Column name to plot on the numerical axis.
    color_column (str, optional): Column name to group by on
        the color dimension.
    color_order (list, optional): List of values within the
        'color_column' for specific color sort.
    categorical_order_by (str or array-like, optional):
        Dimension for ordering the categorical axis. Default 'values'.
        - 'values': Order categorical axis by the numerical
            axis values. Default.
        - 'labels': Order categorical axis by the categorical labels.
        - array-like object (list, tuple, np.array): New labels
            to conform the categorical axis to.
    categorical_order_ascending (bool, optional): Sort order of the
        categorical axis. Default False.
File:      /usr/local/lib/python3.6/site-packages/chartify/_core/plot.py
Type:      method
In [27]:
ch = chartify.Chart(# Your code goes here
                    x_axis_type='categorical',
                    y_axis_type='linear')

ch.set_title('Quantity per country')
ch.set_subtitle('Data description')
ch.set_source_label('Source')
ch.axes.set_xaxis_label('Country')
ch.axes.set_yaxis_label('Quantity')

ch.plot.bar(bar_data, 'country', 'quantity')

ch.show()

Examples

  • Chartify includes many examples. They're a good starting point if you're trying to create a chart that you're unfamiliar with.
In [28]:
# List of available examples
print_public_methods(chartify.examples)
Methods:
axes_axis_tick_format
axes_axis_tick_values
axes_axis_type
callout_box
callout_line
callout_text
chart_blank
chart_labels
chart_layouts
chart_show
chartify
example_data
np
pd
plot_area
plot_bar
plot_bar_grouped
plot_bar_stacked
plot_heatmap
plot_hexbin
plot_histogram
plot_interval
plot_kde
plot_line
plot_lollipop
plot_parallel
plot_scatter
plot_scatter_categorical
plot_text
style_color_palette_accent
style_color_palette_categorical
style_color_palette_custom
style_color_palette_diverging
style_color_palette_sequential
  • Run the appropriate method to see examples and the corresponding code that generates the example.
In [29]:
# chartify.examples.plot_bar()

import chartify

# Generate example data
data = chartify.examples.example_data()

quantity_by_fruit = (data.groupby('fruit')['quantity'].sum().reset_index())

print(quantity_by_fruit.head())

ch = chartify.Chart(blank_labels=True, x_axis_type='categorical')
ch.set_title("Vertical bar plot")
ch.set_subtitle("Automatically sorts by value counts.")
ch.plot.bar(
    data_frame=quantity_by_fruit,
    categorical_columns='fruit',
    numeric_column='quantity')
ch.show()
    fruit  quantity
0   Apple       608
1  Banana      1076
2   Grape       332
3  Orange       862

Bar plot - Horizontal vs. Vertical

  • Your Turn: Copy your bar plot here, but make it horizantal instead of vertical. Look to the example above if you get stuck.
In [30]:
ch = chartify.Chart(x_axis_type='linear',
                    y_axis_type='categorical')

ch.set_title('Quantity per country')
ch.set_subtitle('Data description')
ch.set_source_label('Source')
ch.axes.set_xaxis_label('Quantity')
ch.axes.set_yaxis_label('Country')

ch.plot.bar(bar_data, 'country', 'quantity')

ch.show()

Grouped bar plot

  • Your Turn: Create a grouped bar plot with the data below.
In [31]:
grouped_bar_data = (data.groupby(['country', 'fruit'])[['quantity']].sum()
                    .reset_index()
                   )

grouped_bar_data.head()
Out[31]:
country fruit quantity
0 BR Apple 57
1 BR Banana 30
2 BR Grape 54
3 BR Orange 74
4 CA Apple 144
In [32]:
# Implement the grouped bar plot here.
# Look at the example for help if you get stuck.

ch = chartify.Chart(blank_labels=True,
                    x_axis_type='categorical',
                    y_axis_type='linear')

ch.set_title('Quantity per country and fruit')
ch.set_subtitle('Grouped bar chart')

ch.plot.bar(grouped_bar_data,
            categorical_columns=['fruit', 'country'],
            numeric_column='quantity',
            color_column='country'
           )

ch.show()

show('html') vs. show('png') vs. show('svg')

  • Chartify charts can be rendered as either "HTML" or "PNG" or "SVG" (HTML is the default)
  • HTML output:
    • Is faster and good for iteration.
    • Can be saved as an image by screenshotting, or by clicking the icon on the top right.
    • Will NOT show up in Jupyter notebooks when uploaded to GHE.
  • PNG/SVG output:
    • Is slower and better for the finished product.
    • Can be copy and pasted directly from the jupyter notebook (Right click on the image)
    • Will show up in Jupyter notebooks when uploaded to GHE.
  • See the difference by running the two cells below
In [33]:
(chartify.Chart(blank_labels=True)
.set_title("HTML output")
.set_subtitle("Faster, but will not show up in GHE")
.show()
)
In [34]:
(chartify.Chart(blank_labels=True)
.set_title("SVG output")
.set_subtitle("Slower, but will show up in GHE. Right click to copy + paste.")
.show('svg')
)

Color palette types

  • Chartify includes 4 different color palette types: categorical, accent, sequential, diverging.
  • Note the differences in the examples below
In [35]:
#chartify.examples.style_color_palette_categorical()

import numpy as np
import pandas as pd
import chartify

# Generate example data
data = pd.DataFrame({'x': list(range(100))})
data['y'] = data['x'] * np.random.normal(size=100)
data['z'] = np.random.choice([2, 4, 5], size=100)
data['country'] = np.random.choice(
    ['US', 'GB', 'CA', 'JP', 'BR'], size=100)

# Plot the data
ch = chartify.Chart(blank_labels=True)
ch.style.set_color_palette(palette_type='categorical')
ch.plot.scatter(
    data_frame=data,
    x_column='x',
    y_column='y',
    color_column='country')
ch.set_title("Categorical color palette type")
ch.set_subtitle("Default palette type. Use to differentiate categorical series.")
ch.show()
In [36]:
#chartify.examples.style_color_palette_accent()

import numpy as np
import pandas as pd
import chartify

# Generate example data
data = pd.DataFrame({'x': list(range(100))})
data['y'] = data['x'] * np.random.normal(size=100)
data['z'] = np.random.choice([2, 4, 5], size=100)
data['country'] = np.random.choice(
    ['US', 'GB', 'CA', 'JP', 'BR'], size=100)

# Plot the data
ch = chartify.Chart(blank_labels=True)
ch.style.set_color_palette('accent', accent_values=['US', 'CA'])
ch.plot.scatter(
    data_frame=data,
    x_column='x',
    y_column='y',
    size_column='z',
    color_column='country')
ch.set_title("Accent color palette")
ch.set_subtitle("Highlight specific color values or assign specific colors to values.")
ch.show()
In [37]:
#chartify.examples.style_color_palette_diverging()

import numpy as np
import pandas as pd
import chartify

data = pd.DataFrame({'time': pd.date_range('2015-01-01', '2018-01-01')})
n_days = len(data)
data['Very Unlikely'] = np.array(list(range(n_days))) + np.random.normal(
    0, 10, size=n_days)
data['Unlikely'] = np.array(list(range(n_days))) + np.random.normal(
    0, 10, size=n_days) + 200
data['Neutral'] = np.array(list(range(n_days))) + np.random.normal(
    0, 10, size=n_days) + 500
data['Likely'] = np.array(list(range(n_days))) + np.random.normal(
    0, 10, size=n_days) + 700
data['Very Likely'] = np.array(list(range(n_days))) + np.random.normal(
    0, 10, size=n_days) + 800
data = pd.melt(
    data,
    id_vars=['time'],
    value_vars=data.columns[1:],
    value_name='y',
    var_name=['grouping'])

# Plot the data

ch = chartify.Chart(blank_labels=True, x_axis_type='datetime')
ch.style.set_color_palette(palette_type='diverging')
color_order = [
    'Very Unlikely', 'Unlikely', 'Neutral', 'Likely', 'Very Likely'
]
ch.plot.line(
    data_frame=data.sort_values('time'),
    x_column='time',
    y_column='y',
    color_column='grouping',
    color_order=color_order)  # Your data must be sorted
ch.set_title("Diverging color palette type")
ch.set_subtitle("Palette type for diverging ordered dimensions")
ch.show()
In [38]:
#chartify.examples.style_color_palette_sequential()

import numpy as np
import pandas as pd
import chartify

data = pd.DataFrame({'time': pd.date_range('2015-01-01', '2018-01-01')})
n_days = len(data)
data['1st'] = np.array(list(range(n_days))) + np.random.normal(
    0, 10, size=n_days)
data['2nd'] = np.array(list(range(n_days))) + np.random.normal(
    0, 10, size=n_days) + 200
data['3rd'] = np.array(list(range(n_days))) + np.random.normal(
    0, 10, size=n_days) + 500
data['4th'] = np.array(list(range(n_days))) + np.random.normal(
    0, 10, size=n_days) + 700
data['5th'] = np.array(list(range(n_days))) + np.random.normal(
    0, 10, size=n_days) + 800
data['6th'] = np.array(list(range(n_days))) + np.random.normal(
    0, 10, size=n_days) + 1000
data = pd.melt(
    data,
    id_vars=['time'],
    value_vars=data.columns[1:],
    value_name='y',
    var_name=['grouping'])

# Plot the data
ch = chartify.Chart(blank_labels=True, x_axis_type='datetime')
ch.style.set_color_palette(palette_type='sequential')
ch.plot.line(
    data_frame=data.sort_values('time'),
    x_column='time',
    y_column='y',
    color_column='grouping')
ch.set_title("Sequential color palette type")
ch.set_subtitle("Palette type for sequential ordered dimensions")
ch.show()

Color palettes

  • Chartify includes a set of pre-defined color palettes:
In [39]:
chartify.color_palettes
Out[39]:
Color Palettes: 
'Category20'
'Category10'
'Colorblind'
'Dark2'
'Pastel1'
'RdBu'
'RdGy'
'Greys'
'Greens'
'Blues'
'Reds'
'Oranges'
'All colors'
  • Use .show() to see the colors associated with each:
In [40]:
chartify.color_palettes.show()
Out[40]:

Color Palettes

Category20

'#1f77b4',
'#ff7f0e',
'#2ca02c',
'#d62728',
'#9467bd',
'#8c564b',
'#e377c2',
'#7f7f7f',
'#bcbd22',
'#17becf',
'#aec7e8',
'#ffbb78',
'#98df8a',
'#ff9896',
'#c5b0d5',
'#c49c94',
'#f7b6d2',
'#c7c7c7',
'#dbdb8d',
'#9edae5',

Category10

'#1f77b4',
'#ff7f0e',
'#2ca02c',
'#d62728',
'#9467bd',
'#8c564b',
'#e377c2',
'#7f7f7f',
'#bcbd22',
'#17becf',

Colorblind

'#0072b2',
'#e69f00',
'#f0e442',
'#009e73',
'#56b4e9',
'#d55e00',
'#cc79a7',
'black',

Dark2

'#1b9e77',
'#d95f02',
'#7570b3',
'#e7298a',
'#66a61e',
'#e6ab02',
'#a6761d',
'#666',

Pastel1

'#fbb4ae',
'#b3cde3',
'#ccebc5',
'#decbe4',
'#fed9a6',
'#ffc',
'#e5d8bd',
'#fddaec',
'#f2f2f2',

RdBu

'#67a9cf',
'#f7f7f7',
'#ef8a62',

RdGy

'#404040',
'#bababa',
'white',
'#f4a582',
'#ca0020',

Greys

'#d9d9d9',
'#bdbdbd',
'#969696',
'#737373',
'#525252',
'#252525',
'black',

Greens

'#c7e9c0',
'#a1d99b',
'#74c476',
'#41ab5d',
'#238b45',
'#006d2c',
'#00441b',

Blues

'#c6dbef',
'#9ecae1',
'#6baed6',
'#4292c6',
'#2171b5',
'#08519c',
'#08306b',

Reds

'#fcbba1',
'#fc9272',
'#fb6a4a',
'#ef3b2c',
'#cb181d',
'#a50f15',
'#67000d',

Oranges

'#fdd0a2',
'#fdae6b',
'#fd8d3c',
'#f16913',
'#d94801',
'#a63603',
'#7f2704',

All colors

'LightPink',
'pink',
'crimson',
'PaleVioletRed',
'LavenderBlush',
'HotPink',
'DeepPink',
'MediumVioletRed',
'VioletRed',
'orchid',
'purple',
'thistle',
'plum',
'magenta',
'DarkMagenta',
'violet',
'MediumOrchid',
'DarkViolet',
'DarkOrchid',
'indigo',
'BlueViolet',
'MediumPurple',
'MediumSlateBlue',
'DarkSlateBlue',
'LightSlateBlue',
'SlateBlue',
'DarkBlue',
'navy',
'MediumBlue',
'blue',
'MidnightBlue',
'lavender',
'GhostWhite',
'RoyalBlue',
'CornflowerBlue',
'dark grey',
'LightSteelBlue',
'SlateGray',
'LightSlateGray',
'DodgerBlue',
'AliceBlue',
'SteelBlue',
'LightSkyBlue',
'SkyBlue',
'DeepSkyBlue',
'LightBlue',
'PowderBlue',
'CadetBlue',
'DarkTurquoise',
'DarkCyan',
'cyan',
'DarkSlateGray',
'PaleTurquoise',
'LightCyan',
'azure',
'MediumTurquoise',
'LightSeaGreen',
'turquoise',
'aquamarine',
'MediumAquamarine',
'MediumSpringGreen',
'MintCream',
'SpringGreen',
'MediumSeaGreen',
'SeaGreen',
'green',
'lime',
'ForestGreen',
'DarkSeaGreen',
'LightGreen',
'PaleGreen',
'honeydew',
'DarkGreen',
'LimeGreen',
'LawnGreen',
'chartreuse',
'GreenYellow',
'DarkOliveGreen',
'YellowGreen',
'OliveDrab',
'LightGoldenrodYellow',
'olive',
'beige',
'yellow',
'LightYellow',
'ivory',
'DarkKhaki',
'PaleGoldenrod',
'khaki',
'LemonChiffon',
'gold',
'LightGoldenrod',
'cornsilk',
'goldenrod',
'DarkGoldenrod',
'FloralWhite',
'OldLace',
'wheat',
'orange',
'moccasin',
'PapayaWhip',
'BlanchedAlmond',
'NavajoWhite',
'tan',
'AntiqueWhite',
'burlywood',
'DarkOrange',
'bisque',
'linen',
'peru',
'PeachPuff',
'SandyBrown',
'SaddleBrown',
'chocolate',
'seashell',
'sienna',
'LightSalmon',
'OrangeRed',
'coral',
'DarkSalmon',
'tomato',
'salmon',
'MistyRose',
'black',
'DimGray',
'maroon',
'gray',
'DarkRed',
'brown',
'DarkGray',
'firebrick',
'RosyBrown',
'silver',
'IndianRed',
'LightGray',
'gainsboro',
'LightCoral',
'WhiteSmoke',
'red',
'snow',
'white',
'light grey',
  • Assign the color palettes with .set_color_palette
In [41]:
ch = chartify.Chart(x_axis_type='categorical',
                    blank_labels=True)
ch.style.set_color_palette('categorical', 'Dark2')
ch.plot.bar(data_frame=grouped_bar_data,
            categorical_columns=['fruit', 'country'],
            numeric_column='quantity',
            color_column='fruit')
ch.show()
  • Color palette objects include methods for manipulation. See the examples below:
In [42]:
dark2 = chartify.color_palettes['Dark2']
dark2.show()
Out[42]:

Dark2

'#1b9e77',
'#d95f02',
'#7570b3',
'#e7298a',
'#66a61e',
'#e6ab02',
'#a6761d',
'#666',
  • Sort
In [43]:
sorted_dark2 = dark2.sort_by_hue()
sorted_dark2.show()
Out[43]:

Dark2

'#e7298a',
'#7570b3',
'#1b9e77',
'#66a61e',
'#e6ab02',
'#a6761d',
'#d95f02',
'#666',
  • Expand
In [44]:
dark2.expand_palette(20).show()
Out[44]:

Dark2

'#1b9e77',
'#5a8950',
'#9a7429',
'#d95f02',
'#b8653d',
'#966a78',
'#7570b3',
'#9b58a5',
'#c14198',
'#e7298a',
'#bc5366',
'#917c42',
'#66a61e',
'#91a815',
'#bba90b',
'#e6ab02',
'#c6900f',
'#a6761d',
'#866e41',
'#666',
  • Shift
In [45]:
shifted_dark2 = dark2.shift_palette('white', percent=20)
shifted_dark2.show()
Out[45]:

Dark2

'#47b191',
'#e07e33',
'#8f8bc2',
'#ec52a0',
'#83b749',
'#ebbb33',
'#b79048',
'#838383',
  • Assign the shifted color palette to a chart:
In [46]:
ch = chartify.Chart(x_axis_type='categorical',
                    blank_labels=True)
ch.style.set_color_palette('categorical', shifted_dark2)
ch.plot.bar(data_frame=grouped_bar_data,
            categorical_columns=['fruit', 'country'],
            numeric_column='quantity',
            color_column='fruit')
ch.show()

Layouts

  • Chartify layouts are tailored toward use in slides.
  • Notice how the output changes for each of the slide layout options below:
In [47]:
layout_options = ['slide_100%', 'slide_75%', 'slide_50%', 'slide_25%']
for option in layout_options:
    ch = chartify.Chart(layout=option, blank_labels=True, x_axis_type='categorical')
    ch.set_title('Layout: {}'.format(option))
    ch.plot.bar(data_frame=grouped_bar_data,
            categorical_columns=['fruit', 'country'],
            numeric_column='quantity',
            color_column='fruit')

    ch.show()

Advanced usage with Bokeh

  • Chartify is built on top of another visualization package called Bokeh
  • The example below shows how you can access the Bokeh figure from a Chartify chart object.
In [48]:
ch = chartify.Chart(blank_labels=True, x_axis_type='categorical')
ch.plot.bar(data_frame=grouped_bar_data,
        categorical_columns=['fruit', 'country'],
        numeric_column='quantity',
        color_column='fruit')
ch.figure
Out[48]:
Figure(
id = '5583', …)
  • The following example shows how you can modify attributes not exposed in Chartify by accessing the Bokeh figure. See Bokeh documentation for more details.
In [49]:
ch.figure.xaxis.axis_label_text_font_size = '30pt'
ch.figure.xaxis.axis_label_text_color = 'red'
ch.figure.height = 400
ch.axes.set_xaxis_label('A large xaxis label')
ch.show()
Notebooks AI
Notebooks AI Profile20060