使用散景与字典创建饼图

时间:2018-06-05 10:28:00

标签: python dictionary bokeh

所以我得到了这本词典:

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, .....})

我如何将其变成散景中的条形图?

我查了一下却无法轻易找到它。

2 个答案:

答案 0 :(得分:1)

由于我们没有在较新版本的散景图中提供散景图表,因此您可以使用wedge创建饼图。您需要制作多个字形才能获得图表。它还将涉及获得角度计算以创建正确的楔形 -

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)

答案 1 :(得分:1)

从Bokeh 0.13.0开始,可以使用新的cumsum转换:

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)

enter image description here