Saturday, February 18, 2017

Bar plot in Python using Bokeh


import pandas as pd
from collections import Counter
from datetime import datetime, timedelta
from bokeh.charts import Bar, output_file, show
from bokeh.models.layouts import Column
import numpy as np

try:
    data = pd.read_csv('new.csv')
    scan_col = Counter(data['Scan'])
    values = list()
    keys = list()
   
    for s in scan_col.keys():
        scan_time_total = datetime.strptime("00:00:00","%H:%M:%S")
        scan_time_total = timedelta(hours=scan_time_total.hour, minutes=scan_time_total.minute, seconds=scan_time_total.second)
        for i,v in data['Scan'].iteritems():
            if s == v:
                temp = data['Time'][i]
                temp = datetime.strptime(data['Time'][i],"%H:%M:%S")
                temp = timedelta(hours=temp.hour, minutes=temp.minute, seconds=temp.second)
                scan_time_total += temp
        values.append(scan_time_total.total_seconds()/60)
        keys.append(s)

    output_file("bar.html")
    scan_dict = {'values':values, 'names':keys}
    df = pd.DataFrame(scan_dict)
    p = Bar(df, 'names', values='values', title="Scan vs Time", plot_width=1234, legend=False)
    p.xaxis.axis_label = "Scans"
    p.yaxis.axis_label = "Total Time (minutes)"
   
    values2 = list()
    keys2 = list()
   
    for s in scan_col.keys():
        keys2.append(s)
    for s in scan_col.values():
        values2.append(s)
       
    scan_dict2 = {'values':values2, 'names':keys2}
    df2 = pd.DataFrame(scan_dict2)
    p2 = Bar(df2, 'names', values='values', title="Scan vs Count", plot_width=1234, legend=False)
    p2.xaxis.axis_label = "Scans"
    p2.yaxis.axis_label = "Count"
   
    show(Column(p,p2))
   
except Exception as e:
    print(e)   

This example creates a bar chart with Bokeh, which renders interactive charts to the browser with hover and zoom. As in the Matplotlib version, it summarizes CSV data with pandas first.

Bokeh suits dashboards and web facing visuals where interactivity matters, whereas Matplotlib is often the better choice for static figures in reports.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.