gpt4 book ai didi

javascript - 使用 ajax 更新 Bokeh 图

转载 作者:数据小太阳 更新时间:2023-10-29 06:04:39 24 4
gpt4 key购买 nike

我有一个与 this one 类似的问题.我有一个包含多个元素的网站,例如表格和 Bokeh 图,我想在用户提供特定输入后更新它们。虽然我可以为表格完成此操作,但我不知道如何更新 Bokeh 图。

在下面的示例中,我使用了一个最小的示例,其中用户输入决定了表格的尺寸。所以输出看起来像这样:

enter image description here

表格的更新效果很好,正如预期的那样,但是,我很难相应地更新绘图。我可以使用以下方法轻松初始化它(完整代码可以在本文末尾找到):

@app.route('/')
def index():

# just an initial figure
p = figure(plot_width=150, plot_height=100)

p.line([1, 2, 3], [1, 2, 3])
# save(p, 'testing.html')

script_bok, div_bok = components(p)
return render_template('index.html', div_bok=div_bok, script_bok=script_bok)

然后可以通过以下方式获取用户的选择

@app.route('/_get_table')
def get_table():

nrow = request.args.get('nrow', type=int)
ncol = request.args.get('ncol', type=int)

# the table we want to display
df = pd.DataFrame(np.random.randint(0, 10, size=(nrow, ncol)))

# the updated/new plot
p = figure(plot_width=150, plot_height=100)

p.line(list(range(nrow)), list(range(nrow)))
# save(p, 'testing.html')

script_bok, div_bok = components(p)

# how would I pass those now?

return jsonify(my_table=json.loads(df.to_json(orient="split"))["data"],
columns=[{"title": str(col)} for col in json.loads(df.to_json(orient="split"))["columns"]],
div_bok=div_bok,
script_bok=script_bok)

问题是:我现在如何将新组件提供给 index.html,以便绘图与表格一起更新,但页面上的所有其他元素保持不变?

现在有两个答案可以解决这个问题。我仍然决定使用赏金来找到更好的答案。可以改进的地方:

1) 现在,绘图总是从头开始绘制,理想情况下,只会更新数据。

2)有没有办法避免额外的模板(下面叫update_content.html)?

如果没有其他答案出现,我非常乐意为@Anthonydouc 提供 his nice answer 的分数。 .

这是我的全部代码:

from flask import Flask, render_template, request, jsonify
import pandas as pd
import numpy as np
import json
from bokeh.plotting import figure, show, save
from bokeh.embed import components

# Initialize the Flask application
app = Flask(__name__)


@app.route('/')
def index():

# just an initial figure
p = figure(plot_width=150, plot_height=100)

p.line([1, 2, 3], [1, 2, 3])
# save(p, 'testing.html')

script_bok, div_bok = components(p)
return render_template('index.html', div_bok=div_bok, script_bok=script_bok)


@app.route('/_get_table')
def get_table():

nrow = request.args.get('nrow', type=int)
ncol = request.args.get('ncol', type=int)

# the table we want to display
df = pd.DataFrame(np.random.randint(0, 10, size=(nrow, ncol)))

# the updated/new plot
p = figure(plot_width=150, plot_height=100)

p.line(list(range(nrow)), list(range(nrow)))
# save(p, 'testing.html')

script_bok, div_bok = components(p)

# how would I pass those now?

return jsonify(my_table=json.loads(df.to_json(orient="split"))["data"],
columns=[{"title": str(col)} for col in json.loads(df.to_json(orient="split"))["columns"]],
div_bok=div_bok,
script_bok=script_bok)



if __name__ == '__main__':

app.run(debug=True, threaded=True)

和我的index.html

<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet">
<link href="http://cdn.bokeh.org/bokeh/release/bokeh-0.12.15.min.css" rel="stylesheet" type="text/css">
<link href="http://cdn.bokeh.org/bokeh/release/bokeh-widgets-0.12.15.min.css" rel="stylesheet" type="text/css">
</head>
<body>
<div class="container">
<div class="header">
<h3 class="text-muted">some stuff</h3>
</div>

<hr class="mb-4">
<div class="row">
<div class="col-md-8">
<form id="input_data_form" class="needs-validation" novalidate>
<div class="row">
<div class="col-md-6 mb-3">
<label for="nrow">rows</label>
<input type="number" class="form-control" id="nrow" min="0" step="1" placeholder="" value="2" required>
<div class="invalid-feedback">
please provide an integer
</div>
</div>
<div class="col-md-6 mb-3">
<label for="ncol">columns</label>
<input type="number" class="form-control" id="ncol" min="0" step="1" placeholder="" value="2" required>
<div class="invalid-feedback">
please provide an integer
</div>
</div>
</div>
<div class="form-row text-center">
<div class="col-12">
<button id="calculate" type="submit" class="btn btn-primary">Calculate!</button>
</div>
</div>
</form>
</div>
<div class="col-md-4">

<div class="header">
<h5 class="text-muted">Plot results</h5>
</div>
{{div_bok|safe}}
{{script_bok|safe}}
</div>
</div>

<hr class="mb-4">

<table id="a_nice_table" class="table table-striped"></table>

</div>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js" type="text/javascript"></script>
<script src="http://cdn.bokeh.org/bokeh/release/bokeh-0.12.15.min.js"></script>
<script src="http://cdn.bokeh.org/bokeh/release/bokeh-widgets-0.12.15.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var table = null;
$('#input_data_form').submit(function (event) {
event.preventDefault();
if ($('#input_data_form')[0].checkValidity() === false) {
event.stopPropagation();
if (table !== null) {
table.destroy();
table = null;
$("#a_nice_table").empty();
}
} else {
$.getJSON('/_get_table', {
nrow: $("#nrow").val(),
ncol: $("#ncol").val()

}, function(data) {

//document.body.append($(data.script_bok)[0]);

//$("#bokeh_plot").html(data.div_bok);

if (table !== null) {
table.destroy();
table = null;
$("#a_nice_table").empty();
}
table = $("#a_nice_table").DataTable({
data: data.my_table,
columns: data.columns

});
});
return false;
}
$('#input_data_form').addClass('was-validated');
});

});
</script>
</body>

最佳答案

我已经从你的例子中删除了表格,只专注于更新 Bokeh 图。在此示例中需要注意的重要一点是,每次按下计算时都会重新创建绘图。

现在有三个文件 - 服务器代码 (app.py)、基本模板 (index.html) 和一个只渲染 Bokeh 图的模板 (update_content.html)。这两个模板都需要像往常一样位于模板文件夹中。

“_get_table”端点现在返回包含 Bokeh 图的渲染 html。单击计算按钮将触发回调,进而向此端点提交发布请求。应用程序.py:

from flask import Flask, render_template, request, jsonify
import pandas as pd
import numpy as np
import json
from bokeh.plotting import figure, show, save
from bokeh.embed import components

# Initialize the Flask application
app = Flask(__name__)


@app.route('/')
def index():

# just an initial figure
p = figure(plot_width=150, plot_height=100)

p.line([1, 2, 3], [1, 2, 3])
# save(p, 'testing.html')

script_bok, div_bok = components(p)
return render_template('index.html', div_bok=div_bok, script_bok=script_bok)


@app.route('/_get_table', methods=['GET','POST'])
def get_table():

# extract nrow, ncol via ajax post - contained in request.form
nrow = request.form.get('nrow', type=int)
ncol = request.form.get('ncol', type=int)

# the updated/new plot
p = figure(plot_width=150, plot_height=100)

p.line(list(range(nrow)), list(range(nrow)))

script_bok, div_bok = components(p)

#return rendered html to the browser

return render_template('update_content.html', div_bok=div_bok, script_bok=script_bok)



if __name__ == '__main__':

app.run(debug=True, threaded=True)

索引.html:

<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet">
<link href="http://cdn.bokeh.org/bokeh/release/bokeh-0.12.15.min.css" rel="stylesheet" type="text/css">
<link href="http://cdn.bokeh.org/bokeh/release/bokeh-widgets-0.12.15.min.css" rel="stylesheet" type="text/css">
</head>
<body>
<div class="container">
<div class="header">
<h3 class="text-muted">some stuff</h3>
</div>

<hr class="mb-4">
<div class="row">
<div class="col-md-8">
<form id="input_data_form" class="needs-validation" novalidate>
<div class="row">
<div class="col-md-6 mb-3">
<label for="nrow">rows</label>
<input type="number" class="form-control" id="nrow" min="0" step="1" placeholder="" value="2" required>
<div class="invalid-feedback">
please provide an integer
</div>
</div>
<div class="col-md-6 mb-3">
<label for="ncol">columns</label>
<input type="number" class="form-control" id="ncol" min="0" step="1" placeholder="" value="2" required>
<div class="invalid-feedback">
please provide an integer
</div>
</div>
</div>
<div class="form-row text-center">
<div class="col-12">
<button id="calculate" type="submit" class="btn btn-primary">Calculate!</button>
</div>
</div>
</form>
</div>
<div class="col-md-4">
<div class="header">
<h5 class="text-muted">Plot results</h5>
</div>
<div id="plot-content">
{{div_bok|safe}}
{{script_bok|safe}}
</div>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js" type="text/javascript"></script>
<script src="http://cdn.bokeh.org/bokeh/release/bokeh-0.12.15.min.js"></script>
<script src="http://cdn.bokeh.org/bokeh/release/bokeh-widgets-0.12.15.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#calculate').on('click', function(e){
// prevent page being reset, we are going to update only
// one part of the page.
e.preventDefault()
$.ajax({
url:'./_get_table',
type:'post',
data:{'nrow':$("#nrow").val(),
'ncol':$("#ncol").val()},
success : function(data){
// server returns rendered "update_content.html"
// which is just pure html, use this to replace the existing
// html within the "plot content" div
$('#plot-content').html(data)
}
})
});
});
</script>
</body>

更新内容.html

{{div_bok|safe}}
{{script_bok|safe}}

关于javascript - 使用 ajax 更新 Bokeh 图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50297490/

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