{"cells":[{"metadata":{"trusted":true},"cell_type":"code","source":"from IPython.display import IFrame\nIFrame('https://demo.bokeh.org/movies', width=900, height=800)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**`Bokeh`** is a data visualization library in Python that provides high-performance interactive charts and plots. Bokeh output can be obtained in various mediums like notebook, html and server. It is possible to embed bokeh plots in Django and flask apps.\nWe will be using bokeh for this tutorial\n\nWhat is `Data visualization`??\n\n`Data visualization` is the `graphic` representation of `data`. It involves producing images that communicate relationships among the represented data to `viewers` of the images.","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"# BAR PLOT\n\nBarPlot orBarchart is on eof the most common tyoe of plot.It shows the relationship between a numerical varibale and categorical variable.Barcharts are often confounded with histograms, which is highly different. (It has only a numerical variable as input and shows its distribution)","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"from bokeh.io import output_file, show\nfrom bokeh.models import ColumnDataSource\nfrom bokeh.palettes import Spectral6\nfrom bokeh.plotting import figure\nfrom bokeh.transform import factor_cmap\n\noutput_file(\"bar_colormapped.html\")\n\nfruits = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries']\ncounts = [5, 3, 4, 2, 4, 6]\n\nsource = ColumnDataSource(data=dict(fruits=fruits, counts=counts))\n\np = figure(x_range=fruits, plot_height=350, toolbar_location=None, title=\"Fruit Counts\")\np.vbar(x='fruits', top='counts', width=0.9, source=source, legend_field=\"fruits\",\n       line_color='white', fill_color=factor_cmap('fruits', palette=Spectral6, factors=fruits))\n\np.xgrid.grid_line_color = None\np.y_range.start = 0\np.y_range.end = 9\np.legend.orientation = \"horizontal\"\np.legend.location = \"top_center\"\n\nshow(p)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\nfrom bokeh.io import output_file, show\nfrom bokeh.models import ColumnDataSource\nfrom bokeh.palettes import Spectral6\nfrom bokeh.plotting import figure\n\noutput_file(\"bar_colors.html\")\n\nfruits = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries']\ncounts = [5, 3, 4, 2, 4, 6]\n\nsource = ColumnDataSource(data=dict(fruits=fruits, counts=counts, color=Spectral6))\n\np = figure(x_range=fruits, y_range=(0,9), plot_height=350, title=\"Fruit Counts\",\n           toolbar_location=None, tools=\"\")\n\np.vbar(x='fruits', top='counts', width=0.9, color='color', legend_field=\"fruits\", source=source)\n\np.xgrid.grid_line_color = None\np.legend.orientation = \"horizontal\"\np.legend.location = \"top_center\"\n\nshow(p)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from bokeh.io import output_file, show\nfrom bokeh.models import ColumnDataSource\nfrom bokeh.plotting import figure\nfrom bokeh.transform import dodge\n\noutput_file(\"bar_dodged.html\")\n\nfruits = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries']\nyears = ['2015', '2016', '2017']\n\ndata = {'fruits' : fruits,\n        '2015'   : [2, 1, 4, 3, 2, 4],\n        '2016'   : [5, 3, 3, 2, 4, 6],\n        '2017'   : [3, 2, 4, 4, 5, 3]}\n\nsource = ColumnDataSource(data=data)\n\np = figure(x_range=fruits, y_range=(0, 10), plot_height=350, title=\"Fruit Counts by Year\",\n           toolbar_location=None, tools=\"\")\n\np.vbar(x=dodge('fruits', -0.25, range=p.x_range), top='2015', width=0.2, source=source,\n       color=\"#c9d9d3\", legend_label=\"2015\")\n\np.vbar(x=dodge('fruits',  0.0,  range=p.x_range), top='2016', width=0.2, source=source,\n       color=\"#718dbf\", legend_label=\"2016\")\n\np.vbar(x=dodge('fruits',  0.25, range=p.x_range), top='2017', width=0.2, source=source,\n       color=\"#e84d60\", legend_label=\"2017\")\n\np.x_range.range_padding = 0.1\np.xgrid.grid_line_color = None\np.legend.location = \"top_left\"\np.legend.orientation = \"horizontal\"\n\nshow(p)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Bar range Plot","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"from bokeh.io import output_file, show\nfrom bokeh.models import ColumnDataSource\nfrom bokeh.plotting import figure\nfrom bokeh.sampledata.sprint import sprint\n\noutput_file(\"bar_intervals.html\")\n\nsprint.Year = sprint.Year.astype(str)\ngroup = sprint.groupby('Year')\nsource = ColumnDataSource(group)\n\np = figure(y_range=group, x_range=(9.5,12.7), plot_width=400, plot_height=550, toolbar_location=None,\n           title=\"Time Spreads for Sprint Medalists (by Year)\")\np.hbar(y=\"Year\", left='Time_min', right='Time_max', height=0.4, source=source)\n\np.ygrid.grid_line_color = None\np.xaxis.axis_label = \"Time (seconds)\"\np.outline_line_color = None\n\nshow(p)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Candle Stick","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"\nfrom math import pi\n\nimport pandas as pd\n\nfrom bokeh.plotting import figure, output_file, show\nfrom bokeh.sampledata.stocks import MSFT\n\ndf = pd.DataFrame(MSFT)[:50]\ndf[\"date\"] = pd.to_datetime(df[\"date\"])\n\ninc = df.close > df.open\ndec = df.open > df.close\nw = 12*60*60*1000 # half day in ms\n\nTOOLS = \"pan,wheel_zoom,box_zoom,reset,save\"\n\np = figure(x_axis_type=\"datetime\", tools=TOOLS, plot_width=1000, title = \"MSFT Candlestick\")\np.xaxis.major_label_orientation = pi/4\np.grid.grid_line_alpha=0.3\n\np.segment(df.date, df.high, df.date, df.low, color=\"black\")\np.vbar(df.date[inc], w, df.open[inc], df.close[inc], fill_color=\"#D5E1DD\", line_color=\"black\")\np.vbar(df.date[dec], w, df.open[dec], df.close[dec], fill_color=\"#F2583E\", line_color=\"black\")\n\noutput_file(\"candlestick.html\", title=\"candlestick.py example\")\n\nshow(p)  # open a browser","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Stacked Bar","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"from bokeh.io import output_file, show,output_notebook\nfrom bokeh.plotting import figure\noutput_notebook()\noutput_file(\"bar_stacked.html\")\n\nfruits = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries']\nyears = [\"2015\", \"2016\", \"2017\"]\ncolors = [\"#c9d9d3\", \"#718dbf\", \"#e84d60\"]\n\ndata = {'fruits' : fruits,\n        '2015'   : [2, 1, 4, 3, 2, 4],\n        '2016'   : [5, 3, 4, 2, 4, 6],\n        '2017'   : [3, 2, 4, 4, 5, 3]}\n\np = figure(x_range=fruits, plot_height=250, title=\"Fruit Counts by Year\",\n           toolbar_location=None, tools=\"hover\", tooltips=\"$name @fruits: @$name\")\n\np.vbar_stack(years, x='fruits', width=0.9, color=colors, source=data,\n             legend_label=years)\n\np.y_range.start = 0\np.x_range.range_padding = 0.1\np.xgrid.grid_line_color = None\np.axis.minor_tick_line_color = None\np.outline_line_color = None\np.legend.location = \"top_left\"\np.legend.orientation = \"horizontal\"\n\nshow(p)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Group Bar","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"\nfrom bokeh.io import output_file, show\nfrom bokeh.palettes import Spectral5\nfrom bokeh.plotting import figure\nfrom bokeh.sampledata.autompg import autompg as df\nfrom bokeh.transform import factor_cmap\n\n\ndf.cyl = df.cyl.astype(str)\ngroup = df.groupby('cyl')\n\ncyl_cmap = factor_cmap('cyl', palette=Spectral5, factors=sorted(df.cyl.unique()))\n\np = figure(plot_height=350, x_range=group, title=\"MPG by # Cylinders\",\n           toolbar_location=None, tools=\"\")\n\np.vbar(x='cyl', top='mpg_mean', width=0.9, source=group,\n       line_color=cyl_cmap, fill_color=cyl_cmap)\n\np.y_range.start = 0\np.xgrid.grid_line_color = None\np.xaxis.axis_label = \"some stuff\"\np.xaxis.major_label_orientation = 1.2\np.outline_line_color = None\n\nshow(p)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Histogram","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"A histogram is a graphical display of data using bars of different heights. In a histogram, each bar groups numbers into ranges. Taller bars show that more data falls in that range. A histogram displays the shape and spread of continuous sample data.","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"import numpy as np\nimport scipy.special\n\nfrom bokeh.layouts import gridplot\nfrom bokeh.plotting import figure, output_file, show\n\n\ndef make_plot(title, hist, edges, x, pdf, cdf):\n    p = figure(title=title, tools='', background_fill_color=\"#fafafa\")\n    p.quad(top=hist, bottom=0, left=edges[:-1], right=edges[1:],\n           fill_color=\"navy\", line_color=\"white\", alpha=0.5)\n    p.line(x, pdf, line_color=\"#ff8888\", line_width=4, alpha=0.7, legend_label=\"PDF\")\n    p.line(x, cdf, line_color=\"orange\", line_width=2, alpha=0.7, legend_label=\"CDF\")\n\n    p.y_range.start = 0\n    p.legend.location = \"center_right\"\n    p.legend.background_fill_color = \"#fefefe\"\n    p.xaxis.axis_label = 'x'\n    p.yaxis.axis_label = 'Pr(x)'\n    p.grid.grid_line_color=\"white\"\n    return p\n\n# Normal Distribution\n\nmu, sigma = 0, 0.5\n\nmeasured = np.random.normal(mu, sigma, 1000)\nhist, edges = np.histogram(measured, density=True, bins=50)\n\nx = np.linspace(-2, 2, 1000)\npdf = 1/(sigma * np.sqrt(2*np.pi)) * np.exp(-(x-mu)**2 / (2*sigma**2))\ncdf = (1+scipy.special.erf((x-mu)/np.sqrt(2*sigma**2)))/2\n\np1 = make_plot(\"Normal Distribution (μ=0, σ=0.5)\", hist, edges, x, pdf, cdf)\n\n# Log-Normal Distribution\n\nmu, sigma = 0, 0.5\n\nmeasured = np.random.lognormal(mu, sigma, 1000)\nhist, edges = np.histogram(measured, density=True, bins=50)\n\nx = np.linspace(0.0001, 8.0, 1000)\npdf = 1/(x* sigma * np.sqrt(2*np.pi)) * np.exp(-(np.log(x)-mu)**2 / (2*sigma**2))\ncdf = (1+scipy.special.erf((np.log(x)-mu)/(np.sqrt(2)*sigma)))/2\n\np2 = make_plot(\"Log Normal Distribution (μ=0, σ=0.5)\", hist, edges, x, pdf, cdf)\n\n# Gamma Distribution\n\nk, theta = 7.5, 1.0\n\nmeasured = np.random.gamma(k, theta, 1000)\nhist, edges = np.histogram(measured, density=True, bins=50)\n\nx = np.linspace(0.0001, 20.0, 1000)\npdf = x**(k-1) * np.exp(-x/theta) / (theta**k * scipy.special.gamma(k))\ncdf = scipy.special.gammainc(k, x/theta)\n\np3 = make_plot(\"Gamma Distribution (k=7.5, θ=1)\", hist, edges, x, pdf, cdf)\n\n# Weibull Distribution\n\nlam, k = 1, 1.25\nmeasured = lam*(-np.log(np.random.uniform(0, 1, 1000)))**(1/k)\nhist, edges = np.histogram(measured, density=True, bins=50)\n\nx = np.linspace(0.0001, 8, 1000)\npdf = (k/lam)*(x/lam)**(k-1) * np.exp(-(x/lam)**k)\ncdf = 1 - np.exp(-(x/lam)**k)\n\np4 = make_plot(\"Weibull Distribution (λ=1, k=1.25)\", hist, edges, x, pdf, cdf)\n\noutput_file('histogram.html', title=\"histogram.py example\")\n\nshow(gridplot([p1,p2,p3,p4], ncols=2, plot_width=400, plot_height=400, toolbar_location=None))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# 2D Histogram","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"import numpy as np\n\nfrom bokeh.plotting import figure, show\n#from bokeh.palettes import Blues\n# normal distribution center at x=0 and y=5\nx = np.random.randn(100000)\ny = np.random.randn(100000) + 5\n\nH, xe, ye = np.histogram2d(x, y, bins=100)\n\n# produce an image of the 2d histogram\np = figure(x_range=(min(xe), max(xe)), y_range=(min(ye), max(ye)), title='Image')\n\np.image(image=[H], x=xe[0], y=ye[0], dw=xe[-1] - xe[0], dh=ye[-1] - ye[0], palette=\"Spectral11\")\n\nshow(p)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Distribution Plot","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"def make_plot(title, hist, edges, x, pdf, cdf):\n    p = figure(title=title, tools='', background_fill_color=\"#fafafa\")\n    p.quad(top=hist, bottom=0, left=edges[:-1], right=edges[1:],\n           fill_color=\"navy\", line_color=\"white\", alpha=0.5)\n    p.line(x, pdf, line_color=\"#ff8888\", line_width=4, alpha=0.7, legend_label=\"PDF\")\n    p.line(x, cdf, line_color=\"orange\", line_width=2, alpha=0.7, legend_label=\"CDF\")\n\n    p.y_range.start = 0\n    p.legend.location = \"center_right\"\n    p.legend.background_fill_color = \"#fefefe\"\n    p.xaxis.axis_label = 'x'\n    p.yaxis.axis_label = 'Pr(x)'\n    p.grid.grid_line_color=\"white\"\n    return p\n\n# Normal Distribution\n\nmu, sigma = 0, 0.5\n\nmeasured = np.random.normal(mu, sigma, 1000)\nhist, edges = np.histogram(measured, density=True, bins=50)\n\nx = np.linspace(-2, 2, 1000)\npdf = 1/(sigma * np.sqrt(2*np.pi)) * np.exp(-(x-mu)**2 / (2*sigma**2))\ncdf = (1+scipy.special.erf((x-mu)/np.sqrt(2*sigma**2)))/2\n\np1 = make_plot(\"Normal Distribution (μ=0, σ=0.5)\", hist, edges, x, pdf, cdf)\n\n# Log-Normal Distribution\n\nmu, sigma = 0, 0.5\n\nmeasured = np.random.lognormal(mu, sigma, 1000)\nhist, edges = np.histogram(measured, density=True, bins=50)\n\nx = np.linspace(0.0001, 8.0, 1000)\npdf = 1/(x* sigma * np.sqrt(2*np.pi)) * np.exp(-(np.log(x)-mu)**2 / (2*sigma**2))\ncdf = (1+scipy.special.erf((np.log(x)-mu)/(np.sqrt(2)*sigma)))/2\n\np2 = make_plot(\"Log Normal Distribution (μ=0, σ=0.5)\", hist, edges, x, pdf, cdf)\n\n# Gamma Distribution\n\nk, theta = 7.5, 1.0\n\nmeasured = np.random.gamma(k, theta, 1000)\nhist, edges = np.histogram(measured, density=True, bins=50)\n\nx = np.linspace(0.0001, 20.0, 1000)\npdf = x**(k-1) * np.exp(-x/theta) / (theta**k * scipy.special.gamma(k))\ncdf = scipy.special.gammainc(k, x/theta)\n\np3 = make_plot(\"Gamma Distribution (k=7.5, θ=1)\", hist, edges, x, pdf, cdf)\n\n# Weibull Distribution\n\nlam, k = 1, 1.25\nmeasured = lam*(-np.log(np.random.uniform(0, 1, 1000)))**(1/k)\nhist, edges = np.histogram(measured, density=True, bins=50)\n\nx = np.linspace(0.0001, 8, 1000)\npdf = (k/lam)*(x/lam)**(k-1) * np.exp(-(x/lam)**k)\ncdf = 1 - np.exp(-(x/lam)**k)\n\np4 = make_plot(\"Weibull Distribution (λ=1, k=1.25)\", hist, edges, x, pdf, cdf)\n\noutput_file('histogram.html', title=\"histogram.py example\")\n\nshow(gridplot([p1,p2,p3,p4], ncols=2, plot_width=400, plot_height=400, toolbar_location=None))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Pie Plot","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"A pie chart (or a circle chart) is a circular statistical graphic, which is divided into slices to illustrate numerical proportion. In a pie chart, the arc length of each slice (and consequently its central angle and area), is proportional to the quantity it represents. While it is named for its resemblance to a pie which has been sliced, there are variations on the way it can be presented.\n\nPlotting Pie Chart of Degree and percentage is a feature\n","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"from math import pi\n\nimport pandas as pd\n\nfrom bokeh.io import output_file, show\nfrom bokeh.palettes import Paired\nfrom bokeh.plotting import figure\nfrom bokeh.transform import cumsum\n\noutput_file(\"pie.html\")\n\nx = {\n    'United States': 157,\n    'United Kingdom': 93,\n    'Japan': 89,\n    'China': 63,\n    'Germany': 44,\n    'India': 42,\n    'Italy': 40,\n    'Australia': 35,\n    'Brazil': 32,\n    'France': 31,\n    'Taiwan': 31,\n    'Spain': 29\n}\n\ndata = pd.Series(x).reset_index(name='value').rename(columns={'index':'country'})\ndata['angle'] = data['value']/data['value'].sum() * 2*pi\ndata['color'] = Paired[len(x)]\n\np = figure(plot_height=350, title=\"Pie Chart\", toolbar_location=None,\n           tools=\"hover\", tooltips=\"@country: @value\", x_range=(-0.5, 1.0))\n\np.wedge(x=0, y=1, radius=0.4,\n        start_angle=cumsum('angle', include_zero=True), end_angle=cumsum('angle'),\n        line_color=\"white\", fill_color='color', legend_field='country', source=data)\n\np.axis.axis_label=None\np.axis.visible=False\np.grid.grid_line_color = None\n\nshow(p)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Hex Bin Plot","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"\nimport numpy as np\n\nfrom bokeh.io import output_file, show\nfrom bokeh.models import HoverTool\nfrom bokeh.plotting import figure\n\nn = 500\nx = 2 + 2*np.random.standard_normal(n)\ny = 2 + 2*np.random.standard_normal(n)\n\np = figure(title=\"Hexbin for 500 points\", match_aspect=True,\n           tools=\"wheel_zoom,reset\", background_fill_color='#440154')\np.grid.visible = False\n\nr, bins = p.hexbin(x, y, size=0.5, hover_color=\"pink\", hover_alpha=0.8)\n\np.circle(x, y, color=\"white\", size=1)\n\np.add_tools(HoverTool(\n    tooltips=[(\"count\", \"@c\"), (\"(q,r)\", \"(@q, @r)\")],\n    mode=\"mouse\", point_policy=\"follow_mouse\", renderers=[r]\n))\n\noutput_file(\"hexbin.html\")\n\nshow(p)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Ternary Plot","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"import math\n\nfrom bokeh.io import output_file, show\nfrom bokeh.models import GraphRenderer, Oval, StaticLayoutProvider\nfrom bokeh.palettes import Spectral8\nfrom bokeh.plotting import figure\n\nN = 8\nnode_indices = list(range(N))\n\nplot = figure(title='Graph Layout Demonstration', x_range=(-1.1,1.1), y_range=(-1.1,1.1),\n              tools='', toolbar_location=None)\n\ngraph = GraphRenderer()\n\ngraph.node_renderer.data_source.add(node_indices, 'index')\ngraph.node_renderer.data_source.add(Spectral8, 'color')\ngraph.node_renderer.glyph = Oval(height=0.1, width=0.2, fill_color='color')\n\ngraph.edge_renderer.data_source.data = dict(\n    start=[0]*N,\n    end=node_indices)\n\n### start of layout code\ncirc = [i*2*math.pi/8 for i in node_indices]\nx = [math.cos(i) for i in circ]\ny = [math.sin(i) for i in circ]\n\ngraph_layout = dict(zip(node_indices, zip(x, y)))\ngraph.layout_provider = StaticLayoutProvider(graph_layout=graph_layout)\n\nplot.renderers.append(graph)\n\noutput_file('graph.html')\nshow(plot)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import math\n\nfrom bokeh.io import output_file, show\nfrom bokeh.models import GraphRenderer, Oval, StaticLayoutProvider\nfrom bokeh.palettes import Spectral8\nfrom bokeh.plotting import figure\n\nN = 8\nnode_indices = list(range(N))\n\nplot = figure(title=\"Graph Layout Demonstration\", x_range=(-1.1,1.1), y_range=(-1.1,1.1),\n              tools=\"\", toolbar_location=None)\n\ngraph = GraphRenderer()\n\ngraph.node_renderer.data_source.add(node_indices, 'index')\ngraph.node_renderer.data_source.add(Spectral8, 'color')\ngraph.node_renderer.glyph = Oval(height=0.1, width=0.2, fill_color=\"color\")\n\ngraph.edge_renderer.data_source.data = dict(\n    start=[0]*N,\n    end=node_indices)\n\n### start of layout code\ncirc = [i*2*math.pi/8 for i in node_indices]\nx = [math.cos(i) for i in circ]\ny = [math.sin(i) for i in circ]\ngraph_layout = dict(zip(node_indices, zip(x, y)))\ngraph.layout_provider = StaticLayoutProvider(graph_layout=graph_layout)\n\n### Draw quadratic bezier paths\ndef bezier(start, end, control, steps):\n    return [(1-s)**2*start + 2*(1-s)*s*control + s**2*end for s in steps]\n\nxs, ys = [], []\nsx, sy = graph_layout[0]\nsteps = [i/100. for i in range(100)]\nfor node_index in node_indices:\n    ex, ey = graph_layout[node_index]\n    xs.append(bezier(sx, ex, 0, steps))\n    ys.append(bezier(sy, ey, 0, steps))\ngraph.edge_renderer.data_source.data['xs'] = xs\ngraph.edge_renderer.data_source.data['ys'] = ys\n\nplot.renderers.append(graph)\n\noutput_file(\"graph.html\")\nshow(plot)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import networkx as nx\n\nfrom bokeh.io import output_file, show\nfrom bokeh.plotting import figure, from_networkx\n\nG = nx.karate_club_graph()\n\nplot = figure(title=\"Networkx Integration Demonstration\", x_range=(-1.1,1.1), y_range=(-1.1,1.1),\n              tools=\"\", toolbar_location=None)\n\ngraph = from_networkx(G, nx.spring_layout, scale=2, center=(0,0))\nplot.renderers.append(graph)\n\noutput_file(\"networkx_graph.html\")\nshow(plot)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Scatter Plot","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"import pandas as pd\nimport holoviews as hv\nfrom holoviews import dim, opts\nhv.extension('bokeh')\nmacro_df = pd.read_csv('http://assets.holoviews.org/macro.csv', '\\t')\nkey_dimensions   = [('year', 'Year'), ('country', 'Country')]\nvalue_dimensions = [('unem', 'Unemployment'), ('capmob', 'Capital Mobility'),\n                    ('gdp', 'GDP Growth'), ('trade', 'Trade')]\nmacro = hv.Table(macro_df, key_dimensions, value_dimensions)\n\ngdp_unem_scatter = macro.to.scatter('Year', ['GDP Growth', 'Unemployment'])\noverlay = gdp_unem_scatter.overlay('Country')\n\noverlay.opts(\n    opts.Scatter(color=hv.Cycle('Category20'), line_color='k', size=dim('Unemployment')*1.5,\n                 show_grid=True, width=700, height=400),\n    opts.NdOverlay(legend_position='left', show_frame=False))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from bokeh.plotting import figure, output_file, show\nfrom bokeh.sampledata.iris import flowers\n\ncolormap = {'setosa': 'red', 'versicolor': 'green', 'virginica': 'blue'}\ncolors = [colormap[x] for x in flowers['species']]\n\np = figure(title = \"Iris Morphology\")\np.xaxis.axis_label = 'Petal Length'\np.yaxis.axis_label = 'Petal Width'\n\np.circle(flowers[\"petal_length\"], flowers[\"petal_width\"],\n         color=colors, fill_alpha=0.2, size=10)\n\noutput_file(\"iris.html\", title=\"iris.py example\")\n\nshow(p)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Trendline with error based on pandas dataframe","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"from bokeh.io import  show\nfrom bokeh.models import ColumnDataSource\nfrom bokeh.plotting import figure\nimport pandas as pd\n\nfrom datetime import datetime\n\ndef date_(day):\n    return datetime(2018, 1, day)\n\n\ndf = pd.DataFrame(\n{\n\"date\": [date_(1),date_(2),date_(3),date_(4),date_(5),date_(6),date_(7),date_(8),date_(9),date_(10)],\n\"mean\": [10,8,9, 11,12,6, 8,3,8,7],\n\"std\": [2,1,3,2,1,4, 2,3,1,4]\n})\ndf['mean_p_std'] = df['mean'] + df['std']\ndf['mean_m_std'] = df['mean'] - df['std']\n\nsource = ColumnDataSource(data=df)\n\n# plot = figure(x_axis_type=\"datetime\", plot_width=800, plot_height=350)\n# plot.line('date', 'mean', source=source ,line_color='black', line_width=4)\n\n# plot.patch('date','mean_p_std',alpha=0.5, line_width=2, source=source)\n# plot.patch('date','mean_m_std',alpha=0.5, line_width=2, source=source)\nplot = figure(x_axis_type=\"datetime\", plot_width=800, plot_height=350)\nplot.line('date', 'mean', source=source ,line_color='black', line_width=4)\nx = df['date'].append(df['date'].sort_index(ascending=False))\ny = df['mean_p_std'].append(df['mean_m_std'].sort_index(ascending=False))\nplot.patch(x=x, y=y, alpha=0.5, line_width=2)\nshow(plot)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Line Chart","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# Example similar to line.py, but demoing special data\n# values: masked arrays, nans, and inf\n\nimport numpy as np\n\nfrom bokeh.plotting import figure, output_file, show\n\nx = np.linspace(0, 4*np.pi, 200)\ny1 = np.sin(x)\ny2 = np.cos(x)\n\n# Set high/low values to infinity\ny1[y1>+0.9] = +np.inf\ny1[y1<-0.9] = -np.inf\n\n# Set high values to nan and mask the low\ny2 = np.ma.masked_array(y2, y2<-0.9)\ny2[y2>0.9] = np.nan\n\np = figure(title=\"lines with missing/inf values\")\n\np.line(x, y1, color=\"#2222aa\", line_width=2)\n\np.line(x, y2, color=\"#22aa22\", line_width=2)\n\noutput_file(\"line_missing_data.html\", title=\"line_missing_data.py example\")\n\nshow(p)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\"\"\" Example demonstrating turning lines on and off - with JS only\n\"\"\"\n\nimport numpy as np\n\nfrom bokeh.io import output_file, show\nfrom bokeh.layouts import row\nfrom bokeh.models import CheckboxGroup, CustomJS\nfrom bokeh.palettes import Viridis3\nfrom bokeh.plotting import figure\n\noutput_file(\"line_on_off.html\", title=\"line_on_off.py example\")\n\np = figure()\nprops = dict(line_width=4, line_alpha=0.7)\nx = np.linspace(0, 4 * np.pi, 100)\nl0 = p.line(x, np.sin(x), color=Viridis3[0], legend_label=\"Line 0\", **props)\nl1 = p.line(x, 4 * np.cos(x), color=Viridis3[1], legend_label=\"Line 1\", **props)\nl2 = p.line(x, np.tan(x), color=Viridis3[2], legend_label=\"Line 2\", **props)\n\ncheckbox = CheckboxGroup(labels=[\"Line 0\", \"Line 1\", \"Line 2\"],\n                         active=[0, 1, 2], width=100)\n\ncallback = CustomJS(args=dict(l0=l0, l1=l1, l2=l2, checkbox=checkbox), code=\"\"\"\nl0.visible = 0 in checkbox.active;\nl1.visible = 1 in checkbox.active;\nl2.visible = 2 in checkbox.active;\n\"\"\")\n\ncheckbox.js_on_change('active', callback)\n\nlayout = row(checkbox, p)\nshow(layout)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\"\"\" Example demonstrating the picking of line objects.\n\"\"\"\n\nimport numpy as np\n\nfrom bokeh.models import ColumnDataSource, CustomJS, TapTool\nfrom bokeh.plotting import figure, output_file, show\n\n# The data is setup to have very different scales in x and y, to verify\n# that picking happens in pixels. Different widths are used to test that\n# you can click anywhere on the visible line.\n#\n# Note that the get_view() function used here is not documented and\n# might change in future versions of Bokeh.\nt = np.linspace(0, 0.1, 100)\n\ncode = \"\"\"\n// cb_data = {geometries: ..., source: ...}\nconst view = cb_data.source.selected.get_view();\nconst data = source.data;\nif (view) {\n    const color = view.model.line_color;\n    data['text'] = ['Selected the ' + color + ' line'];\n    data['text_color'] = [color];\n    source.change.emit();\n}\n\"\"\"\n\n# use a source to easily update the text of the text-glyph\nsource = ColumnDataSource(data=dict(text=['No line selected'], text_color=['black']))\n\np = figure(width=600, height=500)\n\nl1 = p.line(t, 100*np.sin(t*50), color='goldenrod', line_width=30)\nl2 = p.line(t, 100*np.sin(t*50+1), color='lightcoral', line_width=20)\nl3 = p.line(t, 100*np.sin(t*50+2), color='royalblue', line_width=10)\n\np.text(0, -100, text_color='text_color', source=source)\n\np.add_tools(TapTool(callback=CustomJS(code=code, args=dict(source=source))))\n\noutput_file(\"line_select.html\", title=\"line_select.py example\")\n\nshow(p)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"A density plot is a representation of the distribution of a numeric variable. It uses a kernel density estimate to show the probability density function of the variable (see more). It is a smoothed version of the histogram and is used in the same concept.**\n\nThe density plot show the distribution of salary","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"# Bubble PLot","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"A bubble plot is a scatterplot where a third dimension is added: the value of an additional numeric variable is represented through the size of the dots. You need 3 numerical variables as input: one is represented by the X axis, one by the Y axis, and one by the dot size.","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Calendar plot","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"A calendar plot is a visualization used to show activity over the course of a long span of time, such as months or years. They're best used when you want to illustrate how some quantity varies depending on the day of the week, or how it trends over time. ","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"!pip install icalendar","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from calendar import Calendar\nfrom calendar import day_abbr as day_abbrs\nfrom calendar import month_name as month_names\n\nfrom bokeh.document import Document\nfrom bokeh.embed import file_html\nfrom bokeh.layouts import gridplot\nfrom bokeh.models import (CategoricalAxis, CategoricalScale, ColumnDataSource,\n                          FactorRange, HoverTool, Plot, Rect, Text,)\nfrom bokeh.resources import INLINE\nfrom bokeh.sampledata.us_holidays import us_holidays\nfrom bokeh.util.browser import view\n\n\ndef make_calendar(year, month, firstweekday=\"Mon\"):\n    firstweekday = list(day_abbrs).index(firstweekday)\n    calendar = Calendar(firstweekday=firstweekday)\n\n    month_days  = [ None if not day else str(day) for day in calendar.itermonthdays(year, month) ]\n    month_weeks = len(month_days)//7\n\n    workday = \"linen\"\n    weekend = \"lightsteelblue\"\n\n    def weekday(date):\n        return (date.weekday() - firstweekday) % 7\n\n    def pick_weekdays(days):\n        return [ days[i % 7] for i in range(firstweekday, firstweekday+7) ]\n\n    day_names = pick_weekdays(day_abbrs)\n    week_days = pick_weekdays([workday]*5 + [weekend]*2)\n\n    source = ColumnDataSource(data=dict(\n        days            = list(day_names)*month_weeks,\n        weeks           = sum([ [str(week)]*7 for week in range(month_weeks) ], []),\n        month_days      = month_days,\n        day_backgrounds = sum([week_days]*month_weeks, []),\n    ))\n\n    holidays = [ (date, summary.replace(\"(US-OPM)\", \"\").strip()) for (date, summary) in us_holidays\n        if date.year == year and date.month == month and \"(US-OPM)\" in summary ]\n\n    holidays_source = ColumnDataSource(data=dict(\n        holidays_days  = [ day_names[weekday(date)] for date, _ in holidays ],\n        holidays_weeks = [ str((weekday(date.replace(day=1)) + date.day) // 7) for date, _ in holidays ],\n        month_holidays = [ summary for _, summary in holidays ],\n    ))\n\n    xdr = FactorRange(factors=list(day_names))\n    ydr = FactorRange(factors=list(reversed([ str(week) for week in range(month_weeks) ])))\n    x_scale, y_scale = CategoricalScale(), CategoricalScale()\n\n    plot = Plot(x_range=xdr, y_range=ydr, x_scale=x_scale, y_scale=y_scale,\n                plot_width=300, plot_height=300, outline_line_color=None)\n    plot.title.text = month_names[month]\n    plot.title.text_font_size = \"16px\"\n    plot.title.text_color = \"darkolivegreen\"\n    plot.title.offset = 25\n    plot.min_border_left = 0\n    plot.min_border_bottom = 5\n\n    rect = Rect(x=\"days\", y=\"weeks\", width=0.9, height=0.9, fill_color=\"day_backgrounds\", line_color=\"silver\")\n    plot.add_glyph(source, rect)\n\n    rect = Rect(x=\"holidays_days\", y=\"holidays_weeks\", width=0.9, height=0.9, fill_color=\"pink\", line_color=\"indianred\")\n    rect_renderer = plot.add_glyph(holidays_source, rect)\n\n    text = Text(x=\"days\", y=\"weeks\", text=\"month_days\", text_align=\"center\", text_baseline=\"middle\")\n    plot.add_glyph(source, text)\n\n    xaxis = CategoricalAxis()\n    xaxis.major_label_text_font_size = \"11px\"\n    xaxis.major_label_standoff = 0\n    xaxis.major_tick_line_color = None\n    xaxis.axis_line_color = None\n    plot.add_layout(xaxis, 'above')\n\n    hover_tool = HoverTool(renderers=[rect_renderer], tooltips=[(\"Holiday\", \"@month_holidays\")])\n    plot.tools.append(hover_tool)\n\n    return plot\n\nmonths = [ [ make_calendar(2014, 3*i + j + 1) for j in range(3) ] for i in range(4) ]\ngrid = gridplot(toolbar_location=None, children=months)\n\ndoc = Document()\ndoc.add_root(grid)\n\nif __name__ == \"__main__\":\n    doc.validate()\n    filename = \"calendars.html\"\n    with open(filename, \"w\") as f:\n        f.write(file_html(doc, INLINE, \"Calendar 2014\"))\n    print(\"Wrote %s\" % filename)\n    view(filename)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Box Plot","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"A box plot is a way of summarizing a set of data measured on an interval scale. It is often used in explanatory data analysis. This type of graph is used to show the shape of the distribution, its central value, and its variability.","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"import numpy as np\nimport pandas as pd\n\nfrom bokeh.plotting import figure, output_file, show\n\n# generate some synthetic time series for six different categories\ncats = list(\"abcdef\")\nyy = np.random.randn(2000)\ng = np.random.choice(cats, 2000)\nfor i, l in enumerate(cats):\n    yy[g == l] += i // 2\ndf = pd.DataFrame(dict(score=yy, group=g))\n\n# find the quartiles and IQR for each category\ngroups = df.groupby('group')\nq1 = groups.quantile(q=0.25)\nq2 = groups.quantile(q=0.5)\nq3 = groups.quantile(q=0.75)\niqr = q3 - q1\nupper = q3 + 1.5*iqr\nlower = q1 - 1.5*iqr\n\n# find the outliers for each category\ndef outliers(group):\n    cat = group.name\n    return group[(group.score > upper.loc[cat]['score']) | (group.score < lower.loc[cat]['score'])]['score']\nout = groups.apply(outliers).dropna()\n\n# prepare outlier data for plotting, we need coordinates for every outlier.\nif not out.empty:\n    outx = []\n    outy = []\n    for keys in out.index:\n        outx.append(keys[0])\n        outy.append(out.loc[keys[0]].loc[keys[1]])\n\np = figure(tools=\"\", background_fill_color=\"#efefef\", x_range=cats, toolbar_location=None)\n\n# if no outliers, shrink lengths of stems to be no longer than the minimums or maximums\nqmin = groups.quantile(q=0.00)\nqmax = groups.quantile(q=1.00)\nupper.score = [min([x,y]) for (x,y) in zip(list(qmax.loc[:,'score']),upper.score)]\nlower.score = [max([x,y]) for (x,y) in zip(list(qmin.loc[:,'score']),lower.score)]\n\n# stems\np.segment(cats, upper.score, cats, q3.score, line_color=\"black\")\np.segment(cats, lower.score, cats, q1.score, line_color=\"black\")\n\n# boxes\np.vbar(cats, 0.7, q2.score, q3.score, fill_color=\"#E08E79\", line_color=\"black\")\np.vbar(cats, 0.7, q1.score, q2.score, fill_color=\"#3B8686\", line_color=\"black\")\n\n# whiskers (almost-0 height rects simpler than segments)\np.rect(cats, lower.score, 0.2, 0.01, line_color=\"black\")\np.rect(cats, upper.score, 0.2, 0.01, line_color=\"black\")\n\n# outliers\nif not out.empty:\n    p.circle(outx, outy, size=6, color=\"#F38630\", fill_alpha=0.6)\n\np.xgrid.grid_line_color = None\np.ygrid.grid_line_color = \"white\"\np.grid.grid_line_width = 2\np.xaxis.major_label_text_font_size=\"16px\"\n\noutput_file(\"boxplot.html\", title=\"boxplot.py example\")\n\nshow(p)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Violin Plot","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"import numpy as np\nimport holoviews as hv\nfrom holoviews import opts\nhv.extension('bokeh')\ngroups = [chr(65+g) for g in np.random.randint(0, 3, 200)]\nviolin = hv.Violin((groups, np.random.randint(0, 5, 200), np.random.randn(200)),\n                    ['Group', 'Category'], 'Value')\nviolin.opts(opts.Violin(height=400, show_legend=False, width=600, violin_color=hv.dim('Category').str()), clone=True)\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Chloropeth in texas","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"import holoviews as hv\nfrom holoviews import opts\nhv.extension('bokeh')\nfrom bokeh.sampledata.us_counties import data as counties\nfrom bokeh.sampledata.unemployment import data as unemployment\n\ncounties = [dict(county, Unemployment=unemployment[cid])\n            for cid, county in counties.items()\n            if county[\"state\"] == \"tx\"]\n\nchoropleth = hv.Polygons(counties, ['lons', 'lats'], [('detailed name', 'County'), 'Unemployment'])\nchoropleth.opts(\n    opts.Polygons(logz=True, tools=['hover'], xaxis=None, yaxis=None,\n                   show_grid=False, show_frame=False, width=500, height=500,\n                   color_index='Unemployment', colorbar=True, toolbar='above', line_color='white'))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Periodic Table with Bokeh","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"\nfrom bokeh.io import output_file, show\nfrom bokeh.plotting import figure\nfrom bokeh.sampledata.periodic_table import elements\nfrom bokeh.transform import dodge, factor_cmap\n\noutput_file(\"periodic.html\")\n\nperiods = [\"I\", \"II\", \"III\", \"IV\", \"V\", \"VI\", \"VII\"]\ngroups = [str(x) for x in range(1, 19)]\n\ndf = elements.copy()\ndf[\"atomic mass\"] = df[\"atomic mass\"].astype(str)\ndf[\"group\"] = df[\"group\"].astype(str)\ndf[\"period\"] = [periods[x-1] for x in df.period]\ndf = df[df.group != \"-\"]\ndf = df[df.symbol != \"Lr\"]\ndf = df[df.symbol != \"Lu\"]\n\ncmap = {\n    \"alkali metal\"         : \"#a6cee3\",\n    \"alkaline earth metal\" : \"#1f78b4\",\n    \"metal\"                : \"#d93b43\",\n    \"halogen\"              : \"#999d9a\",\n    \"metalloid\"            : \"#e08d49\",\n    \"noble gas\"            : \"#eaeaea\",\n    \"nonmetal\"             : \"#f1d4Af\",\n    \"transition metal\"     : \"#599d7A\",\n}\n\nTOOLTIPS = [\n    (\"Name\", \"@name\"),\n    (\"Atomic number\", \"@{atomic number}\"),\n    (\"Atomic mass\", \"@{atomic mass}\"),\n    (\"Type\", \"@metal\"),\n    (\"CPK color\", \"$color[hex, swatch]:CPK\"),\n    (\"Electronic configuration\", \"@{electronic configuration}\"),\n]\n\np = figure(title=\"Periodic Table (omitting LA and AC Series)\", plot_width=1000, plot_height=450,\n           x_range=groups, y_range=list(reversed(periods)),\n           tools=\"hover\", toolbar_location=None, tooltips=TOOLTIPS)\n\nr = p.rect(\"group\", \"period\", 0.95, 0.95, source=df, fill_alpha=0.6, legend_field=\"metal\",\n           color=factor_cmap('metal', palette=list(cmap.values()), factors=list(cmap.keys())))\n\ntext_props = {\"source\": df, \"text_align\": \"left\", \"text_baseline\": \"middle\"}\n\nx = dodge(\"group\", -0.4, range=p.x_range)\n\np.text(x=x, y=\"period\", text=\"symbol\", text_font_style=\"bold\", **text_props)\n\np.text(x=x, y=dodge(\"period\", 0.3, range=p.y_range), text=\"atomic number\",\n       text_font_size=\"11px\", **text_props)\n\np.text(x=x, y=dodge(\"period\", -0.35, range=p.y_range), text=\"name\",\n       text_font_size=\"7px\", **text_props)\n\np.text(x=x, y=dodge(\"period\", -0.2, range=p.y_range), text=\"atomic mass\",\n       text_font_size=\"7px\", **text_props)\n\np.text(x=[\"3\", \"3\"], y=[\"VI\", \"VII\"], text=[\"LA\", \"AC\"], text_align=\"center\", text_baseline=\"middle\")\n\np.outline_line_color = None\np.grid.grid_line_color = None\np.axis.axis_line_color = None\np.axis.major_tick_line_color = None\np.axis.major_label_standoff = 0\np.legend.orientation = \"horizontal\"\np.legend.location =\"top_center\"\np.hover.renderers = [r] # only hover element boxes\n\nshow(p)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Log Plot","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"import numpy as np\n\nfrom bokeh.plotting import figure, output_file, show\n\nx = np.linspace(0.1, 5, 80)\n\np = figure(title=\"log axis example\", y_axis_type=\"log\",\n           x_range=(0, 5), y_range=(0.001, 10**22),\n           background_fill_color=\"#fafafa\")\n\np.line(x, np.sqrt(x), legend_label=\"y=sqrt(x)\",\n       line_color=\"tomato\", line_dash=\"dashed\")\n\np.line(x, x, legend_label=\"y=x\")\np.circle(x, x, legend_label=\"y=x\")\n\np.line(x, x**2, legend_label=\"y=x**2\")\np.circle(x, x**2, legend_label=\"y=x**2\",\n         fill_color=None, line_color=\"olivedrab\")\n\np.line(x, 10**x, legend_label=\"y=10^x\",\n       line_color=\"gold\", line_width=2)\n\np.line(x, x**x, legend_label=\"y=x^x\",\n       line_dash=\"dotted\", line_color=\"indigo\", line_width=2)\n\np.line(x, 10**(x**2), legend_label=\"y=10^(x^2)\",\n       line_color=\"coral\", line_dash=\"dotdash\", line_width=2)\n\np.legend.location = \"top_left\"\n\noutput_file(\"logplot.html\", title=\"log plot example\")\n\nshow(p)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Ridge Plot","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"import colorcet as cc\nfrom numpy import linspace\nfrom scipy.stats.kde import gaussian_kde\n\nfrom bokeh.io import output_file, show\nfrom bokeh.models import ColumnDataSource, FixedTicker, PrintfTickFormatter\nfrom bokeh.plotting import figure\nfrom bokeh.sampledata.perceptions import probly\n\noutput_file(\"ridgeplot.html\")\n\ndef ridge(category, data, scale=20):\n    return list(zip([category]*len(data), scale*data))\n\ncats = list(reversed(probly.keys()))\n\npalette = [cc.rainbow[i*15] for i in range(17)]\n\nx = linspace(-20,110, 500)\n\nsource = ColumnDataSource(data=dict(x=x))\n\np = figure(y_range=cats, plot_width=900, x_range=(-5, 105), toolbar_location=None)\n\nfor i, cat in enumerate(reversed(cats)):\n    pdf = gaussian_kde(probly[cat])\n    y = ridge(cat, pdf(x))\n    source.add(y, cat)\n    p.patch('x', cat, color=palette[i], alpha=0.6, line_color=\"black\", source=source)\n\np.outline_line_color = None\np.background_fill_color = \"#efefef\"\n\np.xaxis.ticker = FixedTicker(ticks=list(range(0, 101, 10)))\np.xaxis.formatter = PrintfTickFormatter(format=\"%d%%\")\n\np.ygrid.grid_line_color = None\np.xgrid.grid_line_color = \"#dddddd\"\np.xgrid.ticker = p.xaxis.ticker\n\np.axis.minor_tick_line_color = None\np.axis.major_tick_line_color = None\np.axis.axis_line_color = None\n\np.y_range.range_padding = 0.12\n\nshow(p)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":" # Plotting Text","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"\nfrom bokeh.layouts import column\nfrom bokeh.models import CustomJS, Slider\nfrom bokeh.plotting import figure, output_file, show\n\naligns    = [\"left\", \"center\", \"right\"]\nbaselines = [\"bottom\", \"middle\", \"top\" ]\n\np = figure(x_range=aligns, y_range=baselines, plot_width=800, plot_height=600,\n           title=\"Variations of multi-line text\", toolbar_location=None)\n\np.background_fill_color = \"lightgrey\"\np.xaxis.axis_label = \"align\"\np.yaxis.axis_label = \"baseline\"\np.axis.major_label_text_font_size = \"18px\"\np.axis.major_label_text_font_style = \"bold italic\"\n\np.xgrid.grid_line_color = None\np.ygrid.grid_line_color = None\n\ntexts = [\n\n'''one''',\n\n'''two\nlines''',\n\n'''lines\nhere:\n3''',\n\n'''here\nare\n4\nlines'''\n\n]\n\ndef xs(cat):\n    return [(cat, -0.3), (cat, -0.1), (cat, 0.1), (cat, 0.3)]\n\ndef ys(cat):\n    return [cat] * 4\n\nrenderers = {}\ni = 0\n\nfor a in aligns:\n    for b in baselines:\n        r = p.text(xs(a), ys(b), texts, text_align=a, text_baseline=b,\n                   text_font_size=\"14px\", text_line_height=1.2)\n        renderers[\"r\" + str(i)] = r\n        i += 1\n\nslider = Slider(title=\"Text Angle\", start=0, end=45, step=1, value=0)\nslider.js_on_change('value', CustomJS(args=renderers, code=\"\"\"\n    var rs = [r0, r1, r2 , r3, r4, r5, r6, r7, r8];\n    for (var i = 0; i < 9; i++) {\n        rs[i].glyph.angle = {value: cb_obj.value, units: \"deg\"}\n    }\n\"\"\"))\n\noutput_file(\"text.html\")\nshow(column(p, slider))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Themed Glyphs","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"import numpy as np\n\nfrom bokeh.io import curdoc, output_file, show\nfrom bokeh.models import (ColumnDataSource, Ellipse, HBar, Line,\n                          LinearAxis, Plot, Scatter, Text, Title,)\nfrom bokeh.models.formatters import BasicTickFormatter\nfrom bokeh.models.tickers import BasicTicker\nfrom bokeh.themes import Theme\nfrom bokeh.transform import dodge\n\ntheme_json = {\n    \"attrs\": {\n        \"Plot\": {\"width\": 400, \"height\": 400, \"background_fill_color\": \"#eeeeee\"},\n        \"Grid\": {\"visible\": False},\n        \"Title\": {\"text\": \"Demo of Themes\"},\n        \"LinearAxis\": {\n            \"axis_line_color\": \"#ffffff\",\n            \"major_tick_line_color\": \"#ffffff\",\n            \"axis_label_text_font_size\": \"10pt\",\n            \"axis_label_text_font_style\": \"bold\",\n        },\n        \"LineGlyph\": {\"line_color\": \"#ee33ee\", \"line_width\": 2},\n        \"FillGlyph\": {\"fill_color\": \"orange\"},\n        \"HatchGlyph\": {\"hatch_pattern\": \"@\", \"hatch_alpha\": 0.8},\n        \"TextGlyph\": {\n            \"text_color\": \"red\",\n            \"text_font_style\": \"bold\",\n            \"text_font\": \"Helvetica\",\n        },\n        \"Ellipse\": {\"fill_color\": \"green\", \"line_color\": \"yellow\", \"fill_alpha\": 0.2},\n    }\n}\n\ncurdoc().theme = Theme(json=theme_json)\n\nx = np.linspace(1, 5, 100)\ny = x + np.sin((x - 1) * np.pi)\nx2 = np.linspace(1.5, 5.5, 5)\nz = x2 + 2 * np.cos((x2 - 1) * np.pi)\n\nsource1 = ColumnDataSource({\"x\": [1, 2, 3, 4, 5], \"y\": [1, 2, 3, 4, 5], \"who\": [\"a\", \"b\", \"c\", \"d\", \"e\"]})\nsource2 = ColumnDataSource({\"x\": x, \"y\": y})\nsource3 = ColumnDataSource({\"x\": x2, \"y\": z})\nsource4 = ColumnDataSource({\"y\": [2.5], \"x\": [0.5]})\n\nplot = Plot(plot_width=300, plot_height=300)\nplot.title = Title(text=\"Themed glyphs\")\n\nxaxis = LinearAxis(ticker=BasicTicker(), formatter=BasicTickFormatter())\nyaxis = LinearAxis(ticker=BasicTicker(), formatter=BasicTickFormatter())\nplot.add_layout(xaxis, \"below\")\nplot.add_layout(yaxis, \"left\")\n\nplot.add_glyph(source1, Scatter(x=\"x\", y=\"y\", marker=\"diamond\", size=20))\nplot.add_glyph(source1, Text(x=dodge(\"x\", -0.2), y=dodge(\"y\", 0.1), text=\"who\"))\nplot.add_glyph(source2, Line(x=\"x\", y=\"y\"))\nplot.add_glyph(source3, Ellipse(x=\"x\", y=\"y\", width=0.2, height=0.3, angle=-0.7))\nplot.add_glyph(source4, glyph=HBar(y=\"y\", right=\"x\", height=1.5))\n\noutput_file(\"theme_glyphs.html\", title=\"themed_glyphs.py example\")\nshow(plot)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Maps","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"from bokeh.plotting import figure, output_file, show\nfrom bokeh.tile_providers import CARTODBPOSITRON, get_provider\n\noutput_file(\"tile_source.html\")\n\n# create plot and add tools\np = figure(x_range=(-2000000, 2000000), y_range=(1000000, 7000000),\n           x_axis_type=\"mercator\", y_axis_type=\"mercator\")\np.add_tile(get_provider(CARTODBPOSITRON))\n\nshow(p)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# I understand it is nowhere close to perfect,I'll keep updating it as soon as I learn more!!","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"# Don't Forget to upvote!!It helps me remain motivated and feedbacks is appreciated:)","execution_count":null}],"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat":4,"nbformat_minor":4}