Reputation: 2492
So I've got this dictionary:
Counter({'United States': 157, 'United Kingdom': 93, 'Japan': 89, 'China': 63,
'Germany': 44, 'India': 42, 'Italy': 40, 'Australia': 35, 'Brazil': 32,
'France': 31, 'Taiwan': 31, 'Spain': 29, .....})
How would I go about making this into a barchart in bokeh?
I looked it up but can't really find it that easily.
Upvotes: 0
Views: 1371
Reputation: 34568
As of Bokeh 0.13.0, this is possible to do using the new cumsum
transform:
from collections import Counter
from math import pi
import pandas as pd
from bokeh.palettes import Category20c
from bokeh.plotting import figure, show
from bokeh.transform import cumsum
x = Counter({
'United States': 157,'United Kingdom': 93,'Japan': 89, 'China': 63,
'Germany': 44,'India': 42, 'Italy': 40,'Australia': 35,'Brazil': 32,
'France': 31,'Taiwan': 31,'Spain': 29
})
data = pd.DataFrame.from_dict(dict(x), orient='index').reset_index()
data = data.rename(index=str, columns={0:'value', 'index':'country'})
data['angle'] = data['value']/sum(x.values()) * 2*pi
data['color'] = Category20c[len(x)]
p = figure(plot_height=350, title="Pie Chart", toolbar_location=None,
tools="hover", tooltips=[("Country", "@country"),("Value", "@value")])
p.wedge(x=0, y=1, radius=0.4,
start_angle=cumsum('angle', include_zero=True), end_angle=cumsum('angle'),
line_color="white", fill_color='color', legend='country', source=data)
p.axis.axis_label=None
p.axis.visible=False
p.grid.grid_line_color = None
show(p)
Upvotes: 1
Reputation: 2103
Since we don't have bokeh charting available in newer versions of bokeh, you can use wedge
to create pie-charts. You need to make multiple glyphs to get the chart. It will also involve getting the angle calculations to create the correct wedges -
from collections import Counter
from bokeh.palettes import Category20c
x = Counter({'United States': 157, 'United Kingdom': 93, 'Japan': 89, 'China': 63,
'Germany': 44, 'India': 42, 'Italy': 40, 'Australia': 35, 'Brazil': 32,
'France': 31, 'Taiwan': 31, 'Spain': 29})
x = pd.DataFrame.from_dict(dict(x), orient='index').reset_index().rename(index=str, \
columns={0:'value', 'index':'country'})
x['val'] = x['value']
x['value'] = x['value']/x['value'].sum()*360.0
x['end']=x['value'].expanding(1).sum()
x['start'] = x['end'].shift(1)
x['start'][0]=0
r=[]
p = figure(plot_height=350, title="PieChart", toolbar_location=None, tools="")
for i in range(len(x)):
r1 = p.wedge(x=0, y=1, radius=0.5,start_angle=x.iloc[i]['start'], end_angle=x.iloc[i]['end'],\
start_angle_units='deg', end_angle_units = 'deg', fill_color=Category20c[20][i],\
legend = x.iloc[i]['country'])
Country = x.iloc[i]['country']
Value = x.iloc[i]['val']
hover = HoverTool(tooltips=[
("Country", "%s" %Country),
("Value", "%s" %Value)
], renderers=[r1])
p.add_tools(hover)
p.xaxis.axis_label=None
p.yaxis.axis_label=None
p.yaxis.visible=False
p.xaxis.visible=False
p.xgrid.grid_line_color = None
p.ygrid.grid_line_color = None
output_notebook()
show(p)
Upvotes: 1