Skip to content

Instantly share code, notes, and snippets.

@afonsobspinto
Created November 7, 2020 18:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save afonsobspinto/24c2e75763ea90032086414f260a9655 to your computer and use it in GitHub Desktop.
Save afonsobspinto/24c2e75763ea90032086414f260a9655 to your computer and use it in GitHub Desktop.
box_plot.py
from math import pi
from bokeh.models.tools import CustomJSHover, HoverTool
import pandas as pd
from bokeh.io import show
from bokeh.models import BasicTicker, ColorBar, LinearColorMapper, Label
from bokeh.plotting import figure
from bokeh.sampledata.unemployment1948 import data
from bokeh.layouts import column
import numpy as np
from bokeh.models.tickers import FixedTicker
import colorcet as cc
def get_heatmap_bar():
min_value = 1
int_value = 5
max_value = 10
ticks = [min_value, int_value, max_value]
top_labels = [None, None, None]
heatmap_label_center = (int_value + max_value) / 2
return get_heatmap_bar_aux(ticks, top_labels, heatmap_label_center)
def get_heatmap_bar_aux(ticks, top_labels, heatmap_label_center):
from bokeh.models.callbacks import CustomJS
from bokeh.models import Label
PLOT_HEIGHT = 5
LABEL_HEIGHT = 4.988
TOP_LABEL_HEIGHT = 5.005
BOX_Y_DIFF = 0.0025
box_width = (ticks[-1] - heatmap_label_center) * 2 - 0.05
b = figure(title="World score", tools="", toolbar_location=None, plot_height=100)
b.segment(x0=ticks[0], y0=PLOT_HEIGHT, x1=ticks[-1], y1=PLOT_HEIGHT, line_color="#808080", line_width=3)
b.vbar(x=heatmap_label_center, top=PLOT_HEIGHT + BOX_Y_DIFF, bottom=PLOT_HEIGHT - BOX_Y_DIFF,
width=box_width, fill_color="black", line_color="black")
for i, tick in enumerate(ticks):
b.rect(x=tick, y=PLOT_HEIGHT, width=0.01, height=0.01, line_color="#808080")
l = Label(x=tick - _get_x_diff(tick), y=LABEL_HEIGHT, text="{:.2f}".format(tick), render_mode='css',
border_line_color=None, border_line_alpha=1.0, text_color='black', text_font_size='8pt')
b.add_layout(l)
if top_labels[i] != None:
lt = Label(x=tick-_get_x_diff(top_labels[i]), y=TOP_LABEL_HEIGHT, text=top_labels[i], render_mode='css',
border_line_color=None, border_line_alpha=1.0, text_color='black', text_font_size='8pt')
b.add_layout(lt)
heatmap_label = Label(x=heatmap_label_center-_get_x_diff('Heatmap'), y=TOP_LABEL_HEIGHT, text='Heatmap', render_mode='css',
border_line_color=None, border_line_alpha=1.0, text_color='black', text_font_size='8pt')
b.add_layout(heatmap_label)
b.title.text_font_style='italic'
#b.title.text_line_height=0.3
#b.title.text_font_size='10px'
#b.title.font = 'roboto'
b.xgrid.grid_line_color = None
b.ygrid.grid_line_color = None
b.yaxis.visible = False
b.xaxis.visible = False
b.outline_line_color = None
b.x_range.range_padding = None
b.y_range.range_padding = 1
b.background_fill_color = None
b.border_fill_color = None
callback = CustomJS(args=dict(xr=b.x_range), code="""
console.log("Hello")
""")
#b.js_on_event(PlotEvent, callback)
b.js_on_change('plot_width', callback)
return b
def _get_x_diff(word):
LETTER_SPACE = 0.06
return len(str(word)) * LETTER_SPACE
data['Year'] = data['Year'].astype(str)
data = data.set_index('Year')
data.drop('Annual', axis=1, inplace=True)
data.columns.name = 'Month'
years = list(data.index)
months = list(data.columns)
# reshape to 1D array or rates with a month and year for each row.
df = pd.DataFrame(data.stack(), columns=['rate']).reset_index()
mapper = LinearColorMapper(palette=cc.palette['diverging_tritanopic_cwr_75_98_c20'], low=3, high=df.rate.max())
mapper_world = LinearColorMapper(palette=cc.palette['linear_blue_95_50_c20'], low=0, high=16)
TOOLS = "hover,save,pan,box_zoom,reset,wheel_zoom"
p = figure(title="US Unemployment ({0} - {1})".format(years[0], years[-1]),
x_range=years, y_range=list(reversed(months)),
x_axis_location="above", plot_width=900, plot_height=400,
tools=TOOLS, toolbar_location='above',
tooltips=[])
customTooltips = CustomJSHover(code='''
var value;
var modified;
modified = value + "Test"
return modified.toString()
''')
p.add_tools(
HoverTool(
tooltips=[
( 'rate', '@rate'),
( 'year', '@Year{custom}'),
],
formatters={
'rate' : 'numeral',
'@Year' : customTooltips,
},
))
p.grid.grid_line_color = None
p.axis.axis_line_color = None
p.axis.major_tick_line_color = None
p.axis.major_label_text_font_size = "7px"
p.axis.major_label_standoff = 0
p.xaxis.major_label_orientation = pi / 3
p.xaxis.axis_label = 'Time'
p.yaxis.axis_label = 'Value'
p.rect(x="Year", y="Month", width=1, height=1,
source=df,
fill_color={'field': 'rate', 'transform': mapper},
line_color=None)
n_ticks = 5
ticks = np.linspace(df.rate.min(), df.rate.max(), n_ticks).round(1)
color_ticks = FixedTicker(ticks=ticks)
color_bar = ColorBar(color_mapper=mapper, major_label_text_font_size="7px",
ticker=color_ticks, title="Gene expression (Score)",
label_standoff=6, border_line_color=None, location=(0, 0), orientation='horizontal')
b = get_heatmap_bar()
show(column(p, b), sizing_mode='stretch_width')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment