简体   繁体   English

如何直接使用Bokeh显示statsmodels Mosaics

[英]How to display statsmodels Mosaics directly with Bokeh

I'm looking to create some mosaic plots to visualize contingency tables. 我正在寻找创建一些镶嵌图以可视化列联表。 Mosaic plots are not (for all I know) natively supported by Bokeh so I'm using the statsmodels library ( link ). Bokeh本身不支持马赛克图(据我所知),因此我正在使用statsmodels库( link )。

mosaicplot

Problem is plots from that library don't extend Bokeh's Figure interface, so I can't get them to show in a webpage. 问题在于该库中的Figure没有扩展Bokeh的Figure界面,因此我无法让它们显示在网页中。 Ideally I want the user to be able to select their variables of interest using drop-down boxes on a webpage: 理想情况下,我希望用户能够使用网页上的下拉框选择感兴趣的变量:

WebUI中

How can the results of statsmodels mosaic be displayed directly by Bokeh? Bokeh如何直接显示statsmodels mosaic的结果?

Bokeh does not support mosaic charts directly, however the mosaic function can returns all the geometric data necessary to have Bokeh render a plot itself. 散景不直接支持镶嵌图,但是mosaic功能可以返回使散景本身绘制图所需的所有几何数据。 Additionally, if you pass ax=None : 此外,如果您传递ax=None

_, rects_dict = mosaic(df, ..., ax=None)

then the generation of the Matplotlib plot will be suppressed. 那么Matplotlib图的生成将被抑制。 Below is a complete example that demonstrates how to use the return rects_dict value from mosaic : 以下是一个完整的示例,演示了如何使用mosaic的return rects_dict值:

import pandas as pd
from statsmodels.graphics.mosaicplot import mosaic
from bokeh.plotting import figure, ColumnDataSource, show
from bokeh.transform import factor_cmap

df = pd.DataFrame({
    'size' : ['small', 'medium', 'medium', 'large', 'small', 'large', 'small', 'medium'],
    'length' : ['long', 'short', 'long', 'short', 'long', 'long', 'short', 'short']
})

_, rects_dict = mosaic(df, ['size', 'length'], gap=0, ax=None)

rects = rects_dict.values()
cats = rects_dict.keys()

source = ColumnDataSource(data=dict(
    x    = [r[0]+r[2]/2 for r in rects], # bokeh wants x center, not corner
    y    = [r[1]+r[3]/2 for r in rects], # bokeh wants y center, not corner
    w    = [r[2]        for r in rects],
    h    = [r[3]        for r in rects],
    size = [c[0]        for c in cats ],
    len  = [c[1]        for c in cats ],
))

fill_cmap = factor_cmap('size', palette="Pastel1_3", factors=['small', 'medium', 'large'])

p = figure(x_range=(0,1), y_range=(0,1), x_axis_location=None, y_axis_location=None,
           tools="", toolbar_location=None, tooltips="@size @len")

p.rect(x='x', y='y', width='w', height='h', line_color="white", source=source,
       fill_color=fill_cmap)

show(p)

This results in the plot below with an interactive hover tooltip that displays the categories. 这将在下面的图表中显示一个交互式的悬停工具提示,以显示类别。 You could also add a colorbar or any other Bokeh interactive features directly in standard Bokeh ways: 您还可以直接以标准Bokeh方式添加颜色条或任何其他Bokeh交互式功能:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM