Aller au contenu

Data Visualization avec Bokeh

from bokeh.io import show, output_notebook
from bokeh.plotting import figure
from bokeh.resources import INLINE
output_notebook(INLINE)

Data

import numpy as np
import pandas as pd
items = ["A", "B", "C", "D", "E"]
sizes = [150, 142, 85, 217, 60]
x = np.linspace(-10, 10, 100)
y = x**2
# data = {"item": items, "size": sizes}

Charts

from bokeh.transform import cumsum
from bokeh.models import ColumnDataSource, DataTable, TableColumn, HoverTool, LabelSet

1. Table

source = ColumnDataSource({"item": items, "size": sizes})

columns = [
    TableColumn(field="item", title="Item"),
    TableColumn(field="size", title="Size",)
]
table = DataTable(source=source, columns=columns, height=200, width=500)

show(table)

2. Barplot

source = ColumnDataSource(data)

barplot = figure(plot_width=800,
                 plot_height=400,
                 x_range=items,
                 title="A simple bar chart")
barplot.vbar(x="item",
             bottom=0,
             top="size",
             color='gray',
             width=0.7,
             source=source)

barplot.xaxis.major_label_orientation = 1
barplot.xgrid.grid_line_color = None
barplot.y_range.start = 0
show(barplot)

3. Pie Chart

data = pd.DataFrame({"item": items, "size": sizes})
data = data.sort_values(by="size")
data['percent'] = data['size']/data['size'].sum() * 100
data['percent']  = data['percent'].apply(lambda x: str(round(x, 2))+'%')
data['angle'] = data['size']/data['size'].sum() * 2*3.14
data['color'] = ['gray' for i in range(len(data))]

source = ColumnDataSource(data)

pie = figure(plot_width=500,
             height=500,
             x_range=(-1, 1),
             title="A simple bar chart")
pie.annular_wedge(x=0,
                  y=1,
                  inner_radius=0.5,
                  outer_radius=0.8,
                  start_angle=cumsum('angle',include_zero=True),
                  end_angle=cumsum('angle'),
                  color='color',
                  alpha=0.7,
                  source=source)

pie.axis.axis_label = None
pie.axis.visible = False
pie.grid.grid_line_color = None
show(pie)

4. Line plot

p = figure(plot_width=1000,
           plot_height=400,
           x_range=[x.min(), x.max()],
           y_range=[y.min(), y.max()],
           title="A simple line plot")
p.line(x=x, y=y)
show(p)

6. Scatterplot

x = np.random.uniform(1, 10, 100)
y = np.random.normal(-5, 5, 100)
scatter = figure(plot_width=800,
                 plot_height=400,
                 x_range=[x.min(), x.max()],
                 y_range=[y.min(), y.max()],
                 title="A simple scatter plot")
scatter.circle(x=x,
             y=y,
             color='gray',
             size=10)

show(scatter)