bokeh hbar example with categorical values = white box - python

I've got code for a simple hbar plot that is stripped down to what I think should be, but shows up as a white box. (I can get the simple example of a line plot working so I know the headers are set up correctly.)
from bokeh.embed import components
from bokeh.plotting import figure
fruits = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries']
counts = [5, 3, 4, 2, 4, 6]
p = figure(plot_height=250, title="Fruit counts",
toolbar_location=None, tools="")
p.hbar(y=fruits, right=counts)
data, div = components(p)
The error in the console is "[Bokeh] could not set initial ranges"
If someone could point me to the documentation about anything needing to be added that would be helpful.

As you are working with categorical data, you need to assign a FactorRange for your y_range. This is done either by p.y_range=FactorRange(factors=fruits) or its shorthand version p.x_range=fruits.
The following example shows the figure corectly:
from bokeh.embed import components
from bokeh.plotting import figure, show
from bokeh.models import FactorRange
fruits = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries']
counts = [5, 3, 4, 2, 4, 6]
p = figure(y_range=FactorRange(factors=fruits), plot_height=250, title="Fruit counts",
toolbar_location=None, tools="")
p.hbar(y=fruits, right=counts)
show(p)

Related

Include Bokeh Tooltips in stacked bar chart

I have the code below. Would anyone be able to let me know how to include tooltips for the bar chart below.
from bokeh.core.properties import value
from bokeh.io import show, output_file
from bokeh.plotting import figure
output_file("stacked.html")
fruits = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries']
years = ["2015", "2016", "2017"]
colors = ["#c9d9d3", "#718dbf", "#e84d60"]
data = {'fruits' : fruits,
'2015' : [2, 1, 4, 3, 2, 4],
'2016' : [5, 3, 4, 2, 4, 6],
'2017' : [3, 2, 4, 4, 5, 3]}
p = figure(x_range=fruits, plot_height=250, title="Fruit Counts by Year",
toolbar_location=None, tools="")
p.vbar_stack(years, x='fruits', width=0.9, color=colors, source=data,
legend=[value(x) for x in years])
p.y_range.start = 0
p.x_range.range_padding = 0.1
p.xgrid.grid_line_color = None
p.axis.minor_tick_line_color = None
p.outline_line_color = None
p.legend.location = "top_left"
p.legend.orientation = "horizontal"
show(p)
Thanks
Michael
You want tooltips to indicate the value by year:
tooltips = [
("fruit", "#fruits"),
("2015:", "#2015"),
("2016:", "#2016"),
("2017:", "#2017"),
]
p = figure(x_range=fruits, plot_height=300, title="Fruit Counts by Year",
tooltips=tooltips,
toolbar_location="right", tools="")
output:
You can add a hovertool by specifying "hover" in the list with tools and adding tooltips to it. You have two kinds of tooltips; "#" which displays sourcedata and $ which correspond to values that are intrinsic to the plot, such as the coordinates of the mouse in data or screen space. Hovertools are nice to use in combination with a ColumnDataSource so also take a look at that. More information on hovertools can be found here.
Adding a hovertool to your plot can be done by changing these lines:
tooltips = [
("fruit", "#fruits"),
("x, y", "$x,$y"),
]
p = figure(x_range=fruits, plot_height=300, title="Fruit Counts by Year",
toolbar_location="right", tools=["hover"], tooltips = tooltips)

Bokeh Position Legend outside plot area for stacked vbar

I have a stacked vbar chart in Bokeh, a simplified version of which can be reproduced with:
from bokeh.plotting import figure
from bokeh.io import show
months = ['JAN', 'FEB', 'MAR']
categories = ["cat1", "cat2", "cat3"]
data = {"month" : months,
"cat1" : [1, 4, 12],
"cat2" : [2, 5, 3],
"cat3" : [5, 6, 1]}
colors = ["#c9d9d3", "#718dbf", "#e84d60"]
p = figure(x_range=months, plot_height=250, title="Categories by month",
toolbar_location=None)
p.vbar_stack(categories, x='month', width=0.9, color=colors, source=data)
show(p)
I want to add a legend to the chart, but my real chart has a lot of categories in the stacks and therefore the legend would be very large, so I want it to be outside the plot area to the right.
There's a SO answer here which explains how to add a legend outside of the plot area, but in the example given each glyph rendered is assigned to a variable which is then labelled and added to a Legend object. I understand how to do that, but I believe the vbar_stack method creates mutliple glyphs in a single call, so I don't know how to label these and add them to a separate Legend object to place outside the chart area?
Alternatively, is there a simpler way to use the legend argument when calling vbar_stack and then locate the legend outside the chart area?
Any help much appreciated.
For anyone interested, have now fixed this using simple indexing of the vbar_stack glyphs. Solution below:
from bokeh.plotting import figure
from bokeh.io import show
from bokeh.models import Legend
months = ['JAN', 'FEB', 'MAR']
categories = ["cat1", "cat2", "cat3"]
data = {"month" : months,
"cat1" : [1, 4, 12],
"cat2" : [2, 5, 3],
"cat3" : [5, 6, 1]}
colors = ["#c9d9d3", "#718dbf", "#e84d60"]
p = figure(x_range=months, plot_height=250, title="Categories by month",
toolbar_location=None)
v = p.vbar_stack(categories, x='month', width=0.9, color=colors, source=data)
legend = Legend(items=[
("cat1", [v[0]]),
("cat2", [v[1]]),
("cat3", [v[2]]),
], location=(0, -30))
p.add_layout(legend, 'right')
show(p)
Thanks Toby Petty for your answer.
I have slightly improved your code so that it automatically graps the categories from the source data and assigns colors. I thought this might be handy as the categories are often not explicitly stored in a variable and have to be taken from the data.
from bokeh.plotting import figure
from bokeh.io import show
from bokeh.models import Legend
from bokeh.palettes import brewer
months = ['JAN', 'FEB', 'MAR']
data = {"month" : months,
"cat1" : [1, 4, 12],
"cat2" : [2, 5, 3],
"cat3" : [5, 6, 1],
"cat4" : [8, 2, 1],
"cat5" : [1, 1, 3]}
categories = list(data.keys())
categories.remove('month')
colors = brewer['YlGnBu'][len(categories)]
p = figure(x_range=months, plot_height=250, title="Categories by month",
toolbar_location=None)
v = p.vbar_stack(categories, x='month', width=0.9, color=colors, source=data)
legend = Legend(items=[(x, [v[i]]) for i, x in enumerate(categories)], location=(0, -30))
p.add_layout(legend, 'right')
show(p)

query bokeh multi_line with markers

I would like to know if there is a way to add markers to multiline for bokeh. I can get the multiple lines but then p.circle() doesn't seem to work on list of lists. Here is a sample:
from bokeh.plotting import figure, show
from bokeh.models import ColumnDataSource
from bokeh.palettes import Spectral6, Spectral11
numlines = 2
mypalette = Spectral6[0:numlines]
data = {'x_values': [[1, 2, 3], [1,2,3]],
'y_values': [[1, 2, 3], [4 ,5, 6]], 'labels': ['a', 'b'], 'line_color': mypalette}
source = ColumnDataSource(data=data)
p = figure()
p.multi_line(xs='x_values', ys='y_values', line_color='line_color', source=source)
show(p)
As of Bokeh 0.13.0 there is not. You would need to call p.circle, p.square, etc. for each "sub" line in the multi-line.

Change label ordering in bokeh heatmap

From the bokeh examples
from bokeh.charts import HeatMap, output_file, show
data = {'fruit': ['apples']*3 + ['bananas']*3 + ['pears']*3,
'fruit_count': [4, 5, 8, 1, 2, 4, 6, 5, 4],
'sample': [1, 2, 3]*3}
hm = HeatMap(data, x='fruit', y='sample', values='fruit_count',
title='Fruits', stat=None)
show(hm)
is there a workaround for changing the order in which the labels are displayed? For example, if I wanted to show pears first?
First, you should not use bokeh.charts. It was deprecated, and has been removed from core Bokeh to a separate bkcharts repo. It is completely unsupported and unmaintained. It will not see any new features, bugfixes, improvements, or documentation. It is a dead end.
There are two good options to create this chart:
1) Use the stable and well-supported bokeh.plotting API. This is slightly more verbose, but gives you explicit control over everything, e.g. the order if the categories. In the code below these are specified as x_range and y_range values to figure:
from bokeh.io import output_file, show
from bokeh.models import ColumnDataSource, LinearColorMapper
from bokeh.palettes import Spectral9
from bokeh.plotting import figure
from bokeh.transform import transform
source = ColumnDataSource(data={
'fruit': ['apples']*3 + ['bananas']*3 + ['pears']*3,
'fruit_count': [4, 5, 8, 1, 2, 4, 6, 5, 4],
'sample': ['1', '2', '3']*3,
})
mapper = LinearColorMapper(palette=Spectral9, low=0, high=8)
p = figure(x_range=['apples', 'bananas', 'pears'], y_range=['1', '2', '3'],
title='Fruits')
p.rect(x='fruit', y='sample', width=1, height=1, line_color=None,
fill_color=transform('fruit_count', mapper), source=source)
show(p)
This yields the output below:
You can find much more information (as well as live examples) about categorical data with Bokeh in the Handling Categorical Data sections of the User's Guide.
2) Look into HoloViews, which is a very high level API on top of Bokeh that is actively maintained by a team, and endorsed by the Bokeh team as well. A simple HeatMap in HoloViews is typically a one-liner as with bokeh.charts.

stacked Bar charts in Bokeh

I am drawing bar charts with Bokeh( http://docs.bokeh.org/en/latest/docs/user_guide.html ). It is an amazing tool but at the same time I think it is a little bit immature currently. I have a stacked bar chart with 30 categories on x axis and 40 classes corresponding to each category. I am not able to find out the function that can enable me to change colors (colors right now are very ambiguous) and align legend to top. Alternatively, if a information box can be opened when someone hovers over that color, that can be helpful. I have a very little clue if that can be done.
http://docs.bokeh.org/en/latest/docs/user_guide/charts.html#bar
My example is similar to this one except that I have many variables.
Any suggestions?
UPDATE:
I tried myself the below solution but it looks like there is some problem with Bar(). It does not recognize Bar().
import bokeh.plotting as bp
data24 =OrderedDict()
for i in range(10):
data24[i] = np.random.randint(2, size=10)
figut = bp.figure(tools="reset, hover")
s1 = figut.Bar(data24, stacked= True,color=colors )
s1.select(dict(type=HoverTool)).tooltips = {"x":"$index"}
Running it I get:
AttributeError: 'Figure' object has no attribute 'Bar'
Here are the bar colors that I am getting. There is no way to distinguish between colors.
I've had a dig in the bokeh source code and it seems that the bokeh.charts.Bar method will except some keyword arguments. These can be properties of the Builder class which includes the palette property, defined here. You should be able to pass this as an argument therefore to Bar.
Bar(...,palette=['red','green','blue'],...)
Just tested this out by modifying the example that bokeh provides:
from collections import OrderedDict
import pandas as pd
from bokeh.charts import Bar, output_file, show
from bokeh.sampledata.olympics2014 import data
df = pd.io.json.json_normalize(data['data'])
# filter by countries with at least one medal and sort
df = df[df['medals.total'] > 0]
df = df.sort("medals.total", ascending=False)
# get the countries and we group the data by medal type
countries = df.abbr.values.tolist()
gold = df['medals.gold'].astype(float).values
silver = df['medals.silver'].astype(float).values
bronze = df['medals.bronze'].astype(float).values
# build a dict containing the grouped data
medals = OrderedDict(bronze=bronze, silver=silver, gold=gold)
output_file("stacked_bar.html")
bar = Bar(
medals, countries, title="Stacked bars", stacked=True,
palette=['brown', 'silver', 'gold'])
show(bar)
Both the original question and other answer are very out of date. The bokeh.charts API was deprecated and removed years ago. For stacked bar charts in modern bokeh, see the section on Handling Categorical Data
Here is a complete example:
from bokeh.core.properties import value
from bokeh.io import show, output_file
from bokeh.plotting import figure
output_file("stacked.html")
fruits = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries']
years = ["2015", "2016", "2017"]
colors = ["#c9d9d3", "#718dbf", "#e84d60"]
data = {'fruits' : fruits,
'2015' : [2, 1, 4, 3, 2, 4],
'2016' : [5, 3, 4, 2, 4, 6],
'2017' : [3, 2, 4, 4, 5, 3]}
p = figure(x_range=fruits, plot_height=250, title="Fruit Counts by Year",
toolbar_location=None, tools="")
p.vbar_stack(years, x='fruits', width=0.9, color=colors, source=data,
legend=[value(x) for x in years])
p.y_range.start = 0
p.x_range.range_padding = 0.1
p.xgrid.grid_line_color = None
p.axis.minor_tick_line_color = None
p.outline_line_color = None
p.legend.location = "top_left"
p.legend.orientation = "horizontal"
show(p)

Categories