javascript - 通过 Flask 到 Json 到 D3 的数据帧
问题描述
我目前正在构建一个烧瓶 webapp 并尝试创建一个 d3 图表。D3 将 json 作为数据输入,所以我通过以下方式将我的数据帧转换为 json:
df = pd.DataFrame({'Name': ['JOHN DOE', 'APPLE INC', 'MIKE LOWRY'],
'Value': ['10', '20','30']})
df_json_output = df.to_json()
然后在 d3 网站上获取示例 d3 treemap 代码后,我只是更改了数据源
从:
// read json data
d3.json("https://raw.githubusercontent.com/holtzy/D3-graph-gallery/master/DATA/data_dendrogram_full.json", function(data) {
至
// read json data
d3.json({{ df_json_putput }}, function(data) {
我的预感是该脚本仅用于获取 json 文件的链接,而不是实际值?没有链接可以吗?但实际上只是将 json 值提供给它?
完整脚本:
<script>
// set the dimensions and margins of the graph
var margin = {top: 10, right: 10, bottom: 10, left: 10},
width = 450 - margin.left - margin.right,
height = 450 - margin.top - margin.bottom;
// append the svg object to the body of the page
var svg = d3.select("#treemap")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")");
// read json data
d3.json({{ df_json_output }}, function(data) {
// Give the data to this cluster layout:
var root = d3.hierarchy(data).sum(function(d){ return d.value}) // Here the size of each leave is given in the 'value' field in input data
// Then d3.treemap computes the position of each element of the hierarchy
d3.treemap()
.size([width, height])
.padding(2)
(root)
// use this information to add rectangles:
svg
.selectAll("rect")
.data(root.leaves())
.enter()
.append("rect")
.attr('x', function (d) { return d.x0; })
.attr('y', function (d) { return d.y0; })
.attr('width', function (d) { return d.x1 - d.x0; })
.attr('height', function (d) { return d.y1 - d.y0; })
.style("stroke", "black")
.style("fill", "slateblue")
// and to add the text labels
svg
.selectAll("text")
.data(root.leaves())
.enter()
.append("text")
.attr("x", function(d){ return d.x0+5}) // +10 to adjust position (more right)
.attr("y", function(d){ return d.y0+20}) // +20 to adjust position (lower)
.text(function(d){ return d.data.name })
.attr("font-size", "15px")
.attr("fill", "white")
})
</script>
解决方案
推荐阅读
- ms-access - Access 数据拉取结果的输出在 SAS 中为 *
- image - Flutter web image_picker没有找到实现
- reactjs - 在 MUI DataGrid 中应用过滤器后显示“无行”消息
- automation - Terraform 更新访问策略
- python - 保存时的 VS Code lint 在远程 (pylint) 上不起作用
- typescript - 带有 Svelte src 的 Svelte-kit 和 NPM 模块
- c - 重新分配结构
- ipfs - ipfs 文件 ls 似乎无法配置为专用网络
- reactjs - MUI 数据表,隐藏搜索图标但仍显示搜索栏
- django - Django Form 将类添加到 div、输入字段和标签