javascript - 使用新数据更新/修改 d3 词云

标签 javascript d3.js word-cloud

我正在尝试弄清楚如何使用 d3.js wordcloud 修改和更新所选数据。

目前,我根据索引键显示来自所选数据的前 10 个结果。我希望能够根据键切换此数据,或者如果我想要前 10 个或后 10 个单词。

到目前为止,这是一个 plnk;

http://plnkr.co/edit/cDTeGDaOoO5bXBZTHlhV?p=preview

我一直在尝试引用这些指南,General Update Pattern, IIIAnimated d3 word cloud .但是,我很难理解如何引入最终更新功能,因为几乎所有提及此功能的指南通常都使用 setTimeout 来演示如何更新,而我的大脑就是无法建立联系。

欢迎提出任何建议!

干杯,

(代码在这里)

var width = 455;
var height = 310;
var fontScale = d3.scale.linear().range([0, 30]);
var fill = d3.scale.category20();

var svg = d3.select("#vis").append("svg")
    .attr("width", width)
    .attr("height", height)
    .append("g")
    .attr("transform", "translate(" + (width / 2) + "," + (height / 2) + ")")
    // .selectAll("text")

d3.json("data.json", function(error, data) {
    if (error) {
        console.log(error)
    }
    else {
        data = data
    }

    function sortObject(obj) {
        var newValue = [];
        var orgS = "MC";
        var dateS = "Jan";
        for (var question = 0; question < data.questions.length; question++) {
            var organization = data.organizations.indexOf(orgS);
            var date = data.dates.indexOf(dateS);
            newValue.push({
                label: data.questions[question],
                value: data.values[question][organization][date]
            });
        }
        newValue.sort(function(a, b) {
            return b.value - a.value;
        });
        newValue.splice(10, 50)
        return newValue;
    }
    var newValue = sortObject();


    fontScale.domain([
        d3.min(newValue, function(d) {
            return d.value
        }),
        d3.max(newValue, function(d) {
            return d.value
        }),
    ]);

    d3.layout.cloud().size([width, height])
        .words(newValue)
        .rotate(0)
        .text(function(d) {
            return d.label;
        })
        .font("Impact")
        .fontSize(function(d) {
            return fontScale(d.value)
        })
        .on("end", draw)
        .start();

    function draw(words) {
        var selectVis = svg.selectAll("text")
            .data(words)
        selectVis
            .enter().append("text")
            .style("font-size", function(d) {
                return fontScale(d.value)
            })
            .style("font-family", "Impact")
            .style("fill", function(d, i) {
                return fill(i);
            })
            .attr("text-anchor", "middle")
            .attr("transform", function(d) {
                return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")";
            })
            .text(function(d) {
                return d.label;
            })

        selectVis
            .transition()
            .duration(600)
            .style("font-size", function(d) {
                return fontScale(d.value)
            })
            .attr("transform", function(d) {
                return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")";
            })
            .style("fill-opacity", 1);

        selectVis.exit()
        .transition()
            .duration(200)
            .style('fill-opacity', 1e-6)
            .attr('font-size', 1)
            .remove();
    }
});

最佳答案

我在您的代码中没有看到任何更新功能,因此我添加了该功能以观察更新的工作原理。

// Add a select elemnt to the page
var dropDown = d3.select("#drop")
    .append("select")
    .attr("name", "food-venues");
// Join with your venues
var foodVenues = data.organizations.map(function(d, i) {
    return d;
})
// Append the venues as options
var options = dropDown.selectAll("option")
    .data(foodVenues)
    .enter()
    .append("option")
    .text(function(d) {
        return d;
    })
    .attr("value", function(d) {
        return d;
    })
// On change call the update function
dropDown.on("change", update);

为了使 d3 词云正确更新,您需要使用所需数据再次计算布局

function update() {
  // Using your function and the value of the venue to filter data
  var filteredData = sortObject(data, this.value);
  // Calculate the new domain with the new values
  fontScale.domain([
    d3.min(newValue, function(d) {
      return d.value
    }),
    d3.max(newValue, function(d) {
      return d.value
    }),
  ]);
  // Calculate the layout with new values
  d3.layout.cloud()
    .size([width, height])
    .words(filteredData)
    .rotate(0)
    .text(function(d) {
      return d.label;
    })
    .font("Impact")
    .fontSize(function(d) {
      return fontScale(d.value)
    })
    .on("end", draw)
    .start();
}

我修改了你的 sortObject 函数以接收一个额外的参数,这是所需的地点:

function sortObject(obj, venue) {
  var newValue = [];
  var orgS = venue || "MC";
  // ....
}

这是工作 plnkr:http://plnkr.co/edit/B20h2bNRkyTtfs4SxE0v?p=preview

您应该能够使用这种方法来更新您想要的限制。您可以添加一个带有事件监听器的复选框,该事件监听器将触发更新功能。

在您的 html 中:

<input checked type="checkbox" id="top" value="true"> <label for="top">Show top words</label>

在你的 javascript 中:

var topCheckbox = d3.select('#top')
  .on("change", function() {
    console.log('update!')
  });

关于javascript - 使用新数据更新/修改 d3 词云,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37572070/

相关文章:

javascript - 如何在另一个 JS 应用程序中导入 blazor 自定义元素?

javascript - 如何使用对象数据在angular2中创建多维数组?

包含子正则表达式的 Javascript 复合正则表达式

javascript - 如何使用 Moment.js 让 D3.js 使用 UTC 时间作为 x 轴

javascript - vuejs + d3 : select returns element, 但 attr() 返回 null

javascript - 在 SVG 中创建线条

r - 是否可以使用 wordcloud2 创建 Shiny 的点击事件?

r - TermDocumentMatrix 有时会抛出错误

r - R 中的词云来自值列表(不是来自文本文档)

javascript - MVC返回多个对象到jquery post数据