gpt4 book ai didi

python - 如何在 python 中创建一个交互式绘图,根据我点击的位置生成一个新绘图?

转载 作者:太空宇宙 更新时间:2023-11-04 02:00:58 24 4
gpt4 key购买 nike

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

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

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

我在 SAS VA 中做过类似的事情。我相信这叫做交互作用。

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

最佳答案

这是一个如何在 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)

结果:

enter image description here

关于python - 如何在 python 中创建一个交互式绘图,根据我点击的位置生成一个新绘图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55722247/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com