如何使用Bokeh创建饼图?

时间:2015-03-22 23:34:27

标签: python bokeh

我想做的就是创建一个饼图。 Bokeh文档涵盖了许多复杂的图表,包括圆环图,但它似乎没有覆盖饼图。

有这方面的例子吗?

最终,图表需要嵌入到网页中,因此我需要利用Bokeh的html嵌入功能。

3 个答案:

答案 0 :(得分:11)

如果输入pandas系列而不是数据帧,Donut图表将返回一个简单的饼图。它也会显示标签!

from bokeh.charts import Donut, show
import pandas as pd
data = pd.Series([0.15,0.4,0.7,1.0], index = list('abcd'))
pie_chart = Donut(data)
show(pie_chart)

here

答案 1 :(得分:9)

以下答案已经过时了。 Donut函数是很久以前弃用和删除的旧bokeh.charts API的一部分。对于任何现代版本的Bokeh(例如0.13或更新版本),您可以使用楔形字形创建饼图,如下所示:

from math import pi

import pandas as pd

from bokeh.io import output_file, show
from bokeh.palettes import Category20c
from bokeh.plotting import figure
from bokeh.transform import cumsum

x = { '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.Series(x).reset_index(name='value').rename(columns={'index':'country'})
data['angle'] = data['value']/data['value'].sum() * 2*pi
data['color'] = Category20c[len(x)]

p = figure(plot_height=350, title="Pie Chart", toolbar_location=None,
        tools="hover", tooltips="@country: @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)

show(p)

enter image description here




以下显示

使用bokeh.plotting界面的Bokeh 0.8.1示例:

from bokeh.plotting import *
from numpy import pi

# define starts/ends for wedges from percentages of a circle
percents = [0, 0.3, 0.4, 0.6, 0.9, 1]
starts = [p*2*pi for p in percents[:-1]]
ends = [p*2*pi for p in percents[1:]]

# a color for each pie piece
colors = ["red", "green", "blue", "orange", "yellow"]

p = figure(x_range=(-1,1), y_range=(-1,1))

p.wedge(x=0, y=0, radius=1, start_angle=starts, end_angle=ends, color=colors)

# display/save everythin  
output_file("pie.html")
show(p)

Bokeh> 0.9将正确计算所有字形的边界区域,而不仅仅是"点样"标记字形,并且不需要显式设置这样的范围。

答案 2 :(得分:1)

感谢上面的答案帮助我。我想添加如何在饼图中添加图例,因为我遇到了一些麻烦。以下只是一个片段。我的饼图只有两个部分。因此,我只是制作了一个饼图,并将其称为楔形两次:

import numpy as np
percentAchieved  = .6
pieFigure = figure(x_range=(-1, 1), y_range=(-1, 1))
starts = [np.pi / 2, np.pi * 2 * percentAchieved + np.pi / 2]
ends = [np.pi / 2+ np.pi * 2 * percentAchieved, np.pi / 2 + 2*np.pi]
pieColors = ['blue', 'red']
#therefore, this first wedge will add a legend entry for the first color 'blue' and label it 'hello'
pieFigure.wedge(x=0, y=0, radius=.7, start_angle=starts, end_angle=ends, color=pieColors, legend="hello")
#this will add a legend entry for the 'red' color and label it 'bye'. Made radius zero to not make 
#another piechart overlapping the original one
pieFigure.wedge(x=0, y=0, radius=0, start_angle=starts, end_angle=ends, color=pieColors[1], legend="bye")