And*_*rew 1 python flask plotly
我以前见过类似的问题但没有答案。
目的是在 Flask 应用程序上显示图像,但配置已更改。
将图表转换为 JSON 且不使用 Fig.show() 时,Plotly 图表上的配置设置如何更改?如果使用了Fig.show(),那么配置将在里面修改。
烧瓶代码:
当然,如果这只是为了显示图表,则会使用Fig.show,但这会将其传递给JSON。
#example flask application with graph
from flask import Flask, render_template, request
import plotly.express as px
import plotly
import numpy as np
import json
#Flask settings.
secret_key = 'verysecretkey123lol' #secret key
app = Flask(__name__)
#simple image
img_rgb = np.array([[[255, 0, 0], [0, 255, 0], [0, 0, 255]],
[[0, 255, 0], [0, 0, 255], [255, 0, 0]]
], dtype=np.uint8)
fig = px.imshow(img_rgb)
#Flask
@app.route("/", methods=['GET', 'POST'])
def create():
image = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder)
return render_template('example.html', image = image)
#Run
if __name__ == "__main__":
app.secret_key = secret_key
app.run(debug = False)
Run Code Online (Sandbox Code Playgroud)
HTML 代码(示例.html):
我已将 Config 添加为下面的 javascript 变量。
<!DOCTYPE html>
<html>
<head lang="en">
<title>Dissertation</title>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>
<body>
<div class="chart" id="image">
<script>
var graphs = {{image | safe}};
var config = {"displaylogo": FALSE, 'modeBarButtonsToAdd': ['drawclosedpath', 'eraseshape']};
Plotly.plot('image', graphs, {});
</script>
</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
任何帮助将不胜感激,谢谢
安德鲁
小智 6
在将绘图嵌入到 Flask 应用程序中时,我很难尝试将配置选项传递给 Plotly。特别是,我想删除应用程序中的模式栏按钮。我从这个相关问题中发现了实现这一目标的方法。
具体来说,在调用 JS 显示绘图的 HTML 代码中,使用命令设置绘图配置Plotly.setPlotConfig()。
使用您的代码示例,您可以设置配置并使用以下命令显示绘图
<body>
<div class="chart" id="image">
<script>
var graphs = {{image | safe}};
var config = {"displaylogo": FALSE, 'modeBarButtonsToAdd': ['drawclosedpath', 'eraseshape']};
Plotly.setPlotConfig(config);
Plotly.plot('image', graphs, {});
</script>
</div>
</body>
Run Code Online (Sandbox Code Playgroud)