目录
  • 什么是 bokeh
  • 在哪使用 bokeh 图
  • 安装bokeh库
  • 导入bokeh库
  • 绘制图表的语法
  • 使用bokeh库主题
  • 图表样式
  • python 中的 bokeh用例
    • 数据
    • 数据说明
    • 饼形图
    • 圆环图
    • 散点图
    • 简单直方图
    • 堆积直方图
  • 不同类型的条形图
    • 简单条形图
    • 堆积条形图
    • 堆积垂直条形图
    • 双向条形图
    • 折线图
    • 棒棒糖图表
    • 面积图
    • bokeh库的布局功能
  • 技术交流

    什么是 bokeh

    bokeh 是 python 中的交互式可视化库。bokeh提供的最佳功能是针对现代 web 浏览器进行演示的高度交互式图形和绘图。bokeh 帮助我们制作出优雅、简洁的图表,其中包含各种图表。

    bokeh 主要侧重于将数据源转换为 json 格式,然后用作 bokehjs 的输入。bokeh的一些最佳功能是:

    • 灵活性: bokeh 也为复杂的用例提供简单的图表和海关图表。
    • 功能强: bokeh 具有易于兼容的特性,可以与 pandas 和 jupyter 笔记本一起使用。
    • 样式: 我们可以控制图表,我们可以使用自定义 javascript 轻松修改图表。
    • 开源: bokeh 提供了大量的示例和想法,并在 berkeley source distribution (bsd) 许可下分发。

    使用bokeh,我们可以轻松地将大数据可视化并以吸引人的优雅方式创建不同的图表。

    在哪使用 bokeh 图

    有很多可视化库,为什么我们只需要使用bokeh?我们可以使用 bokeh 库在网页上嵌入图表。使用bokeh,我们可以将图表嵌入网络、制作实时仪表板和应用程序。bokeh 为图表提供了自己的样式选项和小部件。这是使用 flask 或 django 在网站上嵌入bokeh图的优势。

    安装bokeh库

    用pip安装bokeh库,运行以下命令

    pip install pandas-bokeh
    

    为conda环境安装bokeh库,运行以下命令

    conda install -c patrikhlobil pandas-bokeh
    

    导入bokeh库

    为bokeh库导入必要的包。

    import pandas as pd
    # pip install pandas_bokeh
    import pandas_bokeh
    from bokeh.io import show, output_notebook
    from bokeh.plotting import figure
    pandas_bokeh.output_notebook()
    pd.set_option('plotting.backend', 'pandas_bokeh')
    

    bokeh绘图是一个用于创建交互式视觉效果的界面,我们从中导入 它作为保存我们图表的容器。 figure

    from bokeh.plotting import figure
    

    我们需要以下命令来显示图表。

    from bokeh.io import show, output_notebook
    

    我们需要以下命令来在 jupyter notebook 中显示图表的输出。

    pandas_bokeh.output_notebook()
    

    要将图表嵌入为 html,请运行以下命令。

    pandas_bokeh.output_file(文件名)
    

    hovertool 用于在我们使用鼠标指针悬停在数据上时显示值, columndatasource 是 dataframe 的 bokeh 版本。

    from bokeh.models import hovertool, columndatasource
    

    绘制图表的语法

    使用pandas bokeh

    现在,通过以下代码将bokeh绘图库用于 pandas 数据框。

    dataframe.plot_bokeh()
    

    为bokeh创建 figure 对象

    我们将创建一个图形对象,它只不过是一个保存图表的容器。我们可以给 figure() 对象取任何名字,这里我们给了 fig.

    fig = figure()
    '''
    自定义绘图代码
    '''
    show(fig)
    

    使用 columndatasource 创建图表

    要将 columndatasource 与渲染函数一起使用,我们至少需要传递 3 个参数:

    • x – 包含图表 x 轴数据的 columndatasource 列的名称
    • y – 包含图表 y 轴数据的 columndatasource 列的名称
    • source – columndatasource 列的名称,该列包含我们为 x 轴和 y 轴引用的数据

    要在单独的 html 文件中显示输出图表,请运行以下命令。

    output_file('abc.html')
    
    

    使用bokeh库主题

    bokeh主题有一组预定义的设计,可以将它们应用到您的绘图中。bokeh 提供了五个内置主题。

    • caliber,
    • dark_minimal,
    • light_minimal,
    • night_sky,
    • contrast.

    下图显示了图表在内置主题中的外观。在这里,我采取了不同主题的折线图。

    运行以下代码以使用内置主题绘制图表。

    图表样式

    为了增强图表,我们可以使用不同的属性。对象共有的三组主要属性:

    • 线属性
    • 填充属性
    • 文本属性

    基本造型

    我将只添加自定义图表所需的代码,您可以根据需要添加代码。最后,我将展示带有演示代码的图表,以便清楚地理解。好吧,还有更多属性的详细解释请参见官方文档。

    为图表添加背景颜色。

    fig = figure(background_fill_color="#fafafa")
    

    设置图表宽度和高度的值我们需要在figure()中添加高度和宽度。

    fig = figure(height=350, width=500)
    

    隐藏图表的 x 轴和 y 轴。

    fig.axis.visible=false
    

    隐藏图表的网格颜色。

    fig.grid.grid_line_color = none
    

    要更改图表颜色的强度,我们使用 alpha 。

    fig.background_fill_alpha=0.3
    

    要为图表添加标题,我们需要在 figure() 中添加标题。

    fig = figure(title="abc")
    

    要添加或更改 x 轴和 y 轴标签,请运行以下命令。

    fig.xaxis.axis_label='x-axis'
    fig.yaxis.axis_label='y-axis'
    

    简单样式的演示图表

    x = list(range(11))
    y0 = x
    
    fig = figure(width=500, height=250,title='title',background_fill_color="#fafafa")
    
    fig.circle(x, y0, size=12, color="#53777a", alpha=0.8)
    fig.grid.grid_line_color = none
    fig.xaxis.axis_label='x-axis'
    fig.yaxis.axis_label='y-axis'
    
    show(fig)
    

    使用 bokeh.plotting 界面创建图表的步骤是:

    • 准备数据
    • 创建一个新的情节
    • 为您的数据添加渲染,以及您对绘图的可视化自定义
    • 指定生成输出的位置(在 html 文件中或在 jupyter notebook 中)
    • 显示结果

    python 中的 bokeh用例

    数据

    让我们加载数据并再创建一个特征user id;用户 id 会告诉我们它像用户 1、用户 2 等哪个用户。

    import glob
    path = 'archive' 
    all_files = glob.glob(path + "/*.csv")
    li = []
    usr=0
    for filename in all_files:
        usr+=1
        df = pd.read_csv(filename, index_col=none, header=0)
        df['user id']=usr
        li.append(df)
    df = pd.concat(li, axis=0, ignore_index=true)
    df[:2]
    

    数据说明

    • game completed date-游戏完成的日期和时间
    • team团队- 告诉我们玩家是冒名顶替者还是船员
    • outcome结果- 告诉我们游戏是否赢/输
    • task completed已完成的任务 – 船员完成的任务数
    • all tasks completed – 布尔变量显示所有任务是否由船员完成
    • murdered谋杀- 船员是否被谋杀
    • imposter kills冒名顶替者杀死 – 冒名顶替者的击杀次数
    • game length游戏时长——游戏的总持续时间
    • ejected – 玩家是否被其他玩家驱逐
    • sabotages fixed – 船员修复的破坏次数
    • time to complete all tasks完成所有任务的时间——船员完成任务所用的时间
    • rank change排名变化- 比赛输/赢后排名的变化
    • region/game code地区/游戏代码- 服务器和游戏代码
    • user id用户 id –用户数量。

    注意:本文不包含 eda,但展示了如何在 bokeh 中使用不同的图表

    看看数据的分布。

    df.describe(include='o')
    

    我们将创建一个特征 minute 并从 game lenght 中提取数据。

    df['min'] = df.apply(lambda x : x['game length'].split(" ")[0] , axis = 1)
    df['min'] = df['min'].replace('m', '', regex=true)
    df['min'][:2]
    
    0    07
    1    16
    name: min, dtype: object
    

    现在,我们将替换 murdered 特征的值。

    df['murdered'].replace(['no', 'yes', '-'], ['not murdered', 'murdered', 'missing'],inplace=true)
    

    完成必要的清洁步骤后。首先,让我们看看bokeh中的基本图表。

    饼形图

    检查一下游戏中是否有更多的船员或冒名顶替者,我们有总共 2227 人的数据。

    df_team = df.team.value_counts()
    df_team.plot_bokeh(kind='pie', title='ration of mposter vs crewmate')
    

    如图所示,cremates 占 79%,imposters 占 21%,由此可见 imposter: crewmates 的比例为1:4。冒名顶替者较少,因此有可能赢得大部分比赛。

    圆环图

    检查游戏中是否有更多的船员或冒名顶替者被谋杀。我们将添加两个我们将在图表中使用的功能 angle 和 color。

    from math import pi
    df_mur = df.murdered.value_counts().reset_index().rename(columns={'index': 'murdered', 'murdered': 'value'})
    df_mur['angle'] = df_mur['value']/df_mur['value'].sum() * 2*pi
    df_mur['color'] = ['#3182bd', '#6baed6', '#9ecae1']
    
    df_mur
    

    将用annular_wedge()做一个圆环图。

    from bokeh.transform import cumsum
    
    fig = figure(plot_height=350, 
                 title="ration of murdered vs not murdered", 
                 toolbar_location=none,
    
    tools="hover", tooltips="@murdered: @value", x_range=(-.5, .5))
    fig.annular_wedge(x=0, y=1, inner_radius=0.15, 
                      outer_radius=0.25, direction="anticlock",
    
    start_angle=cumsum('angle', include_zero=true),
                      end_angle=cumsum('angle'),
    
    line_color="white", fill_color='color', legend_label='murdered', source=df_mur)
    
    fig.axis.axis_label=none
    fig.axis.visible=false
    fig.grid.grid_line_color = none
    show(fig)
    

    大多数人在游戏中被谋杀,但大部分数据丢失。所以我们不能说大多数人是在游戏中被谋杀的。

    散点图

    首先,将创建 sabotages fixed 和 minutes 的数据框,并更改列名并在其中添加 t。

    df_min = pd.crosstab(df['min'], df['sabotages fixed']).reset_index()
    df_min = df_min.rename(columns={0.0:'0t', 1.0:'1t',
                           2.0:'2t',3.0:'3t',4.0:'4t',5.0:'5t'
                        })
    df_min[:2]
    

    将 3 次破坏固定为 0,1 和 2 并创建一个数据框。

    df_0 = df_min[['min', '0t']]
    df_1 = df_min[['min', '1t']]
    df_2 = df_min[['min', '2t']]
    

    要制作只有一个图例的简单散点图,我们可以传递数据并使用scatter()它来制作图表。

    df_min.plot_bokeh.scatter(x='min', y='1t')
    

    要制作包含多个图例的散点图,我们需要使用圆圈;这是图形对象的一种方法。圆圈是bokeh提供的众多绘图样式之一,您可以使用三角形或更多。

    fig = figure(title='sabotages fixed vs minutes', 
                 tools= 'hover', 
                 toolbar_location="above", 
                 toolbar_sticky=false)
    fig.circle(x="min",y='0t', 
             size=12, alpha=0.5, 
             color="#f78888", 
             legend_label='0t', 
             source=df_0),
    fig.circle(x="min",y='1t', 
             size=12, alpha=0.5, 
             color="blue", 
             legend_label='1t', 
             source=df_1),
    fig.circle(x="min",y='2t', 
             size=12, alpha=0.5, 
             color="#626262", 
             legend_label='2t', 
             source=df_2),
    show(fig)
    

    简单直方图

    看看游戏之间的分钟分布。将用hist来绘制直方图。

    df_minutes = df['min'].astype('int64')
    df_minutes.plot_bokeh(kind='hist', title='distribution of minutes')
    

    大多数比赛有6分钟到14分钟的时间。

    堆积直方图

    看看游戏长度是否会增加,因此冒名顶替者和船员会减少还是增加。我们将使用 hist来制作堆叠直方图。

    df_gm_te = pd.crosstab(df['game length'], df['team'])
    df_gm_te
    

    df_gm_te.plot_bokeh.hist(title='gamelegth vs imposter/crewmate', figsize=(750, 350))
    

    bokeh中的堆叠直方图

    冒名顶替者不倾向于长时间玩游戏,他们只想杀死所有火葬并赢得游戏。

    不同类型的条形图

    简单条形图

    看看给定的任务是否由人完成。如果所有任务都完成,那么自动火葬将获胜。

    df_tc = pd.dataframe(df['task completed'].value_counts())[1:].sort_index().rename(columns={'task completed': 'count'})
    df_tc.plot_bokeh(kind='bar', y='count', title='how many people have completed given task?', figsize=(750, 350))
    

    bokeh中的条形图

    完成最多的任务是 7 个,完成最少的任务是 10 个。

    堆积条形图

    看看谁赢了:冒名顶替者或火葬。我一直觉得冒名顶替者获胜最多,因为他们只有一份工作可以杀死所有人。

    df1 = pd.crosstab(df['team'], df['outcome'])
    df1.plot_bokeh.bar(title='who wins: imposter or crewmates',stacked=true,
    figsize=(550, 350))
    

    bokeh中的堆积条形图

    冒名顶替者比 crewmates 赢得更多。imposter赢得或输掉比赛没有太大区别,价值非常接近。很多情况下,他们有5个火葬场和4个冒名顶替者。

    堆积垂直条形图

    完成任务会不会赢得比赛让我们拭目以待。

    df['all tasks completed'].replace(['yes','no'], ['tasks completed','tasks not completed'], inplace=true)
    
    df2 = pd.crosstab(df['outcome'], df['all tasks completed'])
    df2.plot_bokeh.barh(title='completeing task: win or loss', stacked=true,
    figsize=(650, 350))
    

    bokeh中的堆积条形图

    完成任务将自动赢得火葬。完成任务赢得比赛的人数更多。

    双向条形图

    用双向条形图看看用户是赢了还是输了。要制作双向条形图,我们需要将一个度量设为负值,这里我们将损失特征设为负值。

    df_user = pd.crosstab(df['user id'], df['outcome']).reset_index()
    df_user['loss'] = df_user['loss']*-1
    df_user['user id'] = (df_user.index+1).astype(str) + ' user'
    df_user = df_user.set_index('user id')
    df_user[:2]
    

    现在完成上面的过程后,我们只需要barh() 在两个方向上制作一个条形图即可。

    df_user.plot_bokeh.barh(title='users: won or defeat')
    

    bokeh中的双向条形图

    从图表中,我们可以轻松区分用户是被击败还是赢得了比赛。

    折线图

    看看游戏中火化的排出比例。我们将line 用来制作折线图。

    df_crewmate = df[df['team'] == 'crewmate']
    df_t_ej = pd.crosstab(df_crewmate['user id'], df_crewmate['ejected']).reset_index()
    df_t_ej = df_t_ej[['no','yes']]
    df_t_ej.plot_bokeh.line(title='cremates memebers: ejected vs minutes', figsize=(750, 350))
    

    bokeh中的折线图

    没有被逐出游戏的成员存在很大差异。

    棒棒糖图表

    将获胜的前 10 名用户的图表可视化。我在所有用户 id 中添加了一个用户字符串。数据框看起来像这样。

    df_user_new = pd.crosstab(df['user id'], df['outcome']).reset_index().sort_values(by='win', ascending=false)[:10]
    df_user_new['user id'] = (df_user_new.index+1).astype(str) + ' user'
    df_user_new[:2]
    

    在此图表中,我们将从图表中删除 x 轴和 y 轴网格线。为了制作棒棒糖图表,我们需要结合 segment() 和circle()。

    x = df_user_new['win']
    
    factors = df_user_new['user id'] #.values
    fig = figure(title="top 10 users: win", toolbar_location=none,tools="hover", tooltips="@x",
    y_range=factors, x_range=[0,75],
    plot_width=750, plot_height=350)
    
    fig.segment(0, factors, x, factors, line_width=2, line_color="#3182bd")
    fig.circle(x, factors, size=15, fill_color="#9ecae1", line_color="#3182bd", line_width=3)
    fig.xgrid.grid_line_color = none
    fig.ygrid.grid_line_color = none
    show(fig)
    

    bokeh中的棒棒糖图

    面积图

    看看在这段时间(分钟)内修复了多少破坏事件。在这里为了简单起见,我们将只看到两个破坏活动 0th 和 1st。

    from bokeh.models import columndatasource
    from bokeh.plotting import figure, output_file, show
    
    # data
    df_min = pd.crosstab(df['min'], df['sabotages fixed']).reset_index()
    df_min = df_min.rename(columns={0.0:'0t', 1.0:'1t',2.0:'2t',3.0:'3t',4.0:'4t',5.0:'5t'})
    
    # chart
    names = ['0t','1t']
    source = columndatasource(data=dict(x = df_min.min,
                                        y0 = df_min['0t'],
                                        y1 = df_min['1t']))
    
    fig = figure(width=400, height=400, title='sabotages fied vs minutes')
    fig.varea_stack(['y0','y1'], x='x', color=("grey", "lightgrey"),legend_label=names, source=source)
    
    fig.grid.grid_line_color = none
    fig.xaxis.axis_label='minutes'
    
    show(fig)
    

    bokeh中的面积图

    随着时间的增加,破坏活动会减少。

    到目前为止,我们已经看到了bokeh中的所有基本图表,现在看看如何在bokeh中使用布局。这将帮助我们创建仪表板或应用程序。因此,我们可以将特定用例的所有信息集中在一个地方。

    bokeh库的布局功能

    layout 函数将让我们构建一个由绘图和小部件组成的网格。我们可以在一个布局中拥有尽可能多的行和列或网格。

    有许多可用的布局选项:

    • 如果要垂直显示图,请使用**column()**函数。
    • 如果要水平显示图,请使用**row()**函数。
    • 如果您希望以网格方式绘制图形,请使用**gridplot()**函数。
    • 如果您希望图表以最佳方式放置,请使用**layout()**函数

    取一个虚拟数据。

    from bokeh.io import output_file, show
    from bokeh.layouts import row,column
    from bokeh.plotting import figure
    output_file("layout.html")
    x = list(range(11))
    y0 = x
    y1 = [10 - i for i in x]
    y2 = [abs(i - 5) for i in x]
    # create three plots
    s1 = figure(width=250, height=250, background_fill_color="#fafafa")
    s1.circle(x, y0, size=12, color="#53777a", alpha=0.8)
    s2 = figure(width=250, height=250, background_fill_color="#fafafa")
    s2.triangle(x, y1, size=12, color="#c02942", alpha=0.8)
    s3 = figure(width=250, height=250, background_fill_color="#fafafa")
    s3.square(x, y2, size=12, color="#d95b43", alpha=0.8)
    

    如果我们使用 column() 函数,输出将如下所示。

    show(column(s1, s2, s3))
    

    如果我们使用 row() 函数,输出将如下所示。

    # 将结果排成一行并显示
    show(row(s1, s2, s3))
    

    在 bokeh 中制作仪表板布局。在这里我拍了三张图表,一张是棒棒糖图,另外两张是bokeh的饼图。

    在bokeh中设置布局的主要逻辑是我们希望如何设置图表。创建一个如下图所示的设计。

    layout = grid([[fig1],
                   [fig2, fig3]])
    
    

    在 bokeh 中运行仪表板布局的整个代码。

    from bokeh.io import output_file, show
    from bokeh.plotting import figure
    from bokeh.layouts import column, grid
    # 1 layout
    df_user_new = pd.crosstab(df['user id'], df['outcome']).reset_index().sort_values(by='win', ascending=false)[:10]
    df_user_new['user id'] = (df_user_new.index+1).astype(str) + ' user'
    x = df_user_new['win']
    factors = df_user_new['user id'] 
    fig1 = figure(title="top 10 users: win", toolbar_location=none,
                  tools="hover", tooltips="@x",
                  y_range=factors, x_range=[0,75], 
                  width=700, height=250)
    fig1.segment(0, factors, x, factors, line_width=2, line_color="#3182bd")
    fig1.circle(x, factors, size=15, fill_color="#9ecae1", line_color="#3182bd", line_width=3)
    # 2 layout
    df_mur = df.murdered.value_counts().reset_index().rename(columns={'index': 'murdered', 'murdered': 'value'})
    df_mur['angle'] = df_mur['value']/df_mur['value'].sum() * 2*pi
    df_mur['color'] = ['#3182bd', '#6baed6', '#9ecae1']
    fig2 = figure(height=300,width=400, title="ration of murdered vs not murdered", 
                  toolbar_location=none, tools="hover", tooltips="@murdered: @value", x_range=(-.5, .5))
    fig2.annular_wedge(x=0, y=1,  inner_radius=0.15, outer_radius=0.25, direction="anticlock",
                       start_angle=cumsum('angle', include_zero=true), end_angle=cumsum('angle'),
                       line_color="white", fill_color='color', legend_label='murdered', source=df_mur)
    # 3 layout
    df_team = pd.dataframe(df.team.value_counts()).reset_index().rename(columns={'index': 'team', 'team': 'value'})
    df_team['angle'] = df_team['value']/df_team['value'].sum() * 2*pi
    df_team['color'] = ['#3182bd', '#6baed6']
    
    fig3 = figure(height=300, width=300, title="ration of cremates vs imposter",  
                  toolbar_location=none, tools="hover", tooltips="@team: @value", x_range=(-.5, .5))
    fig3.annular_wedge(x=0, y=1,  inner_radius=0.15, outer_radius=0.25, direction="anticlock",
                       start_angle=cumsum('angle', include_zero=true), end_angle=cumsum('angle'),
                       line_color="white", fill_color='color', legend_label='team', source=df_team)
    # styling
    for fig in [fig1, fig2, fig3]:
            fig.grid.grid_line_color = none
    for fig in [fig2, fig3]:
            fig.axis.visible=false
            fig.axis.axis_label=none
    layout = grid([
                    [fig1],
                    [fig2, fig3]
           ])
    show(layout)
    
    

    技术交流

    欢迎转载、收藏、有所收获点赞支持一下!

    到此这篇关于python库 bokeh 数据可视化实用指南的文章就介绍到这了,更多相关python bokeh数据可视化内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!