Include Bokeh Tooltips in stacked bar chart - python

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)

Related

bokeh hbar example with categorical values = white box

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)

How to customize parallel categories diagram colors with plotly ? Python edition

I'm trying to perform a full colored custom parallel categories diagram from Plotly but I can't. The documentation about the subject is utterly empty : https://plotly.github.io/plotly.py-docs/generated/plotly.graph_objects.parcats.line.colorbar.html and I did not find a example.
I currently have this
And this is what I want (thank you Paint)
3 Columns, 1 with only one categorie ('Base' here), 2 with 2 categories ('10' and '15' here)
Thank you in advance
From examples in documentations here and the output (if you are in jupyter) of go.Sankey.link? you could check that you can modify the color of every link using color.
import plotly.graph_objects as go
fig = go.Figure(data=[go.Sankey(
node = dict(
pad = 15,
thickness = 20,
line = dict(color = "black", width = 0.5),
label = ["A1", "A2", "B1", "B2", "C1", "C2"],
color = "blue"
),
link = dict(
source = [0, 1, 0, 2, 3, 3], # indices correspond to labels, eg A1, A2, A2, B1, ...
target = [2, 3, 3, 4, 4, 5],
value = [8, 4, 2, 8, 4, 2],
color = ["red", "green", "orange", "red", "yellow", "green"]
))])
fig.show()

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)

Error vbar_stack in Bokeh Python

I am a newbie in Bokeh, I want to try vbar_stack in Bokeh and follow the code in their documentation following below:
from bokeh.core.properties import value
from bokeh.io import show, output_file
from bokeh.models import ColumnDataSource
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]}
source = ColumnDataSource(data=data)
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=source,
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)
I got this error after run the code:
AttributeError Traceback (most recent call last)
<ipython-input-152-49fb8bdc8de2> in <module>()
20 toolbar_location=None, tools="")
21
---> 22 p.vbar_stack(years, x='fruits', width=0.9, color=colors, source=source,
23 legend=[value(x) for x in years])
24
AttributeError: 'Figure' object has no attribute 'vbar_stack'
I have tried to upgrade my bokeh to Ver. 0.12.10 (newest), however it did not work.
Your version of Bokeh is too old (the version you are using is from before vbar_stack was added). You need to update to a newer version. If you think you are already at a new enough version then it is likely you have some confusion between multiple virutalenv or conda environments, and are not loading the version of Bokeh you intend. Alternatively, you have some kind of install corruption (delete everything bokeh-related in site-packages and reinstall).

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