【问题标题】:How do I create an interactive plot in python that generates a new plot depending on where i clicked?如何在 python 中创建一个交互式绘图,根据我单击的位置生成一个新绘图?
【发布时间】:2023-03-14 11:55:01
【问题描述】:

我有跨商店、每个月以及不同类别产品的销售数据。

假设我在任一轴上都有跨商店和月份的销售量热图。

现在,当我在与特定商店和月份对应的位置单击热图时,我需要生成一个新的条形图,以显示该月和商店中每个类别的销售量。

我在 SAS VA 中做过类似的事情。我相信它被称为交互效应。

我已经尝试搜索 matplotlib 的文档,但并没有得到任何有用的东西。

【问题讨论】:

    标签: python matplotlib plotly bokeh


    【解决方案1】:

    这是一个如何在 Bokeh v1.1.0 中执行此操作的示例

    from bokeh.plotting import figure, show
    from bokeh.models import TapTool, CustomJS, ColumnDataSource, Row, ColorBar, LinearColorMapper, BasicTicker
    from bokeh.models.sources import ColumnDataSource
    from bokeh.transform import transform
    from bokeh.palettes import Viridis256
    import random
    
    stores = ["store 1", "store 2", "store 3"]
    months = ["january", "fabruary", "march"]
    x = ["store 1", "store 2", "store 3", "store 1", "store 2", "store 3", "store 1", "store 2", "store 3"]
    y = ["january", "january", "january", "fabruary", "fabruary", "fabruary", "march", "march", "march"]
    colors = ["#0B486B", "#79BD9A", "#CFF09E", "#79BD9A", "#0B486B", "#79BD9A", "#CFF09E", "#79BD9A", "#0B486B" ]
    
    p1 = figure(title = "Categorical Heatmap", tools = "tap", toolbar_location = None,
                x_range = stores, y_range = months)
    p1.rect(x = x, y = y, color = colors, width = 1, height = 1)
    
    categories = ['shoes', 'pants', 'suits']
    category_sales = {}
    for store in stores:
        category_sales[store] = {}
        for month in months:
            category_sales[store][month] = [random.choice([i for i in range(10000)]) for r in range(3)]
    
    dummy_category_sales = [1000, 1100, 1200]
    data = {'x': categories, 'y': dummy_category_sales}
    source = ColumnDataSource(data)
    
    p2 = figure(x_range = categories)
    bars = p2.vbar(x = 'x', top = 'y', source = source, bottom = 0, width = 0.5)
    bars.visible = False
    
    code = '''if (cb_data.source.selected.indices.length > 0){
                bars.visible = true;
                selected_index = cb_data.source.selected.indices[0];    
                store = cb_data.source.data['x'][selected_index]
                month = cb_data.source.data['y'][selected_index]
    
                bars.data_source.data['y'] = category_sales[store][month]
                bars.data_source.change.emit(); 
            }'''
    
    p1.select_one(TapTool).callback = CustomJS(args = dict(bars = bars, category_sales = category_sales), code = code)
    
    plots = Row(p1, p2)
    show(plots)
    

    结果:

    【讨论】:

      猜你喜欢
      • 2019-11-14
      • 2015-10-10
      • 1970-01-01
      • 2020-07-27
      • 2013-06-29
      • 1970-01-01
      • 1970-01-01
      • 2018-07-27
      • 1970-01-01
      相关资源
      最近更新 更多