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)
Related
As per the Plotly website, in a simple line chart one can change the legend entry from the column name to a manually specified string of text. For example, this code results in the following chart:
import pandas as pd
import plotly.express as px
df = pd.DataFrame(dict(
x = [1, 2, 3, 4],
y = [2, 3, 4, 3]
))
fig = px.line(
df,
x="x",
y="y",
width=800, height=600,
labels={
"y": "Series"
},
)
fig.show()
label changed:
However, when one plots multiple columns to the line chart, this label specification no longer works. There is no error message, but the legend entries are simply not changed. See this example and output:
import pandas as pd
import plotly.express as px
df = pd.DataFrame(dict(
x = [1, 2, 3, 4],
y1 = [2, 3, 4, 3],
y2 = [2, 4, 6, 8]
))
fig = px.line(
df,
x="x",
y=["y1", "y2"],
width=800, height=600,
labels={
"y1": "Series 1",
"y2": "Series 2"
},
)
fig.show()
legend entries not changed:
Is this a bug, or am I missing something? Any idea how this can be fixed?
In case anybody read my previous post, I did some more digging and found the solution to this issue. At the heart, the labels one sees over on the right in the legend are attributes known as "names" and not "labels". Searching for how to revise those names, I came across another post about this issue with a solution Legend Label Update. Using that information, here is a revised version of your program.
import pandas as pd
import plotly.express as px
df = pd.DataFrame(dict(
x = [1, 2, 3, 4],
y1 = [2, 3, 4, 3],
y2 = [2, 4, 6, 8]
))
fig = px.line(df, x="x", y=["y1", "y2"], width=800, height=600)
fig.update_layout(legend_title_text='Variable', xaxis_title="X", yaxis_title="Series")
newnames = {'y1':'Series 1', 'y2': 'Series 2'} # From the other post
fig.for_each_trace(lambda t: t.update(name = newnames[t.name]))
fig.show()
Following is a sample graph.
Try that out to see if that addresses your situation.
Regards.
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)
I want to have a scatter plot and a (base)line on the same figure. And I want to use HoverTool only on the circles of scatter but not on the line. Is it possible?
With the code below I get tooltips with index: 0 and (x, y): (???, ???) when I hover on the line (any part of the line). But the index: 0 data in source is totally different ((x, y): (1, 2))...
df = pd.DataFrame({'a':[1, 3, 6, 9], 'b':[2, 3, 5, 8]})
from bokeh.models import HoverTool
import bokeh.plotting as bplt
TOOLS = ['box_zoom', 'box_select', 'wheel_zoom', 'reset', 'pan', 'resize', 'save']
source = bplt.ColumnDataSource(data=df)
hover = HoverTool(tooltips=[("index", "$index"), ("(x, y)", "(#a, #b)")])
p = bplt.figure(plot_width=600, plot_height=600, tools=TOOLS+[hover],
title="My sample bokeh plot", webgl=True)
p.circle('a', 'b', size=10, source=source)
p.line([0, 10], [0, 10], color='red')
bplt.save(p, 'c:/_teszt.html')
Thank you!!
To limit which renderers you want the HoverTool is active on (by default it's active on all) you can either set a name attr on your glyphs, then specify which names you want your HoverTool to be active on:
p.circle('a', 'b', size=10, name='circle', source=source)
hover = HoverTool(names=['circle'])
docs:
http://docs.bokeh.org/en/latest/docs/reference/models/tools.html#bokeh.models.tools.HoverTool.names
or you can add the renderers to the HoverTool.
circle = p.circle('a', 'b', size=10, source=source)
hover = HoverTool(renderers=['circle'])
docs:
http://docs.bokeh.org/en/latest/docs/reference/models/tools.html#bokeh.models.tools.HoverTool.renderers
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)
I would like to click-and-drag the scatter points the points of a bokeh scatter plot. Any ideas how to do this?
(edit: this is an example of what I'd like to do)
For an example of a scatter, the code below generates the scatter plot chart found half-way through this page.
from bokeh.plotting import figure, output_file, show
# create a Figure object
p = figure(width=300, height=300, tools="pan,reset,save")
# add a Circle renderer to this figure
p.circle([1, 2.5, 3, 2], [2, 3, 1, 1.5], radius=0.3, alpha=0.5)
# specify how to output the plot(s)
output_file("foo.html")
# display the figure
show(p)
Multi-gesture edit tools are only a recent addition, landing in version 0.12.14. You can find much more information in the Edit Tools section of the User's Guide.
Specifically to be able to move points as described in the OP, use the PointDrawTool:
Here is a complete example you can run that also has a data table showing the updated coordinates of the glyphs as they are moved (you will need to activate the tool in the toolbar first, it is off by default):
from bokeh.plotting import figure, output_file, show, Column
from bokeh.models import DataTable, TableColumn, PointDrawTool, ColumnDataSource
output_file("tools_point_draw.html")
p = figure(x_range=(0, 10), y_range=(0, 10), tools=[],
title='Point Draw Tool')
p.background_fill_color = 'lightgrey'
source = ColumnDataSource({
'x': [1, 5, 9], 'y': [1, 5, 9], 'color': ['red', 'green', 'yellow']
})
renderer = p.scatter(x='x', y='y', source=source, color='color', size=10)
columns = [TableColumn(field="x", title="x"),
TableColumn(field="y", title="y"),
TableColumn(field='color', title='color')]
table = DataTable(source=source, columns=columns, editable=True, height=200)
draw_tool = PointDrawTool(renderers=[renderer], empty_value='black')
p.add_tools(draw_tool)
p.toolbar.active_tap = draw_tool
show(Column(p, table))