createSentimentChart = function(sentences, method) {
document.querySelector('#sentiment-bars').innerHTML = "";
const format = d3.format(".3f");
const margin = ({top: 30, right: 0, bottom: 10, left: 30});
const svg = d3.select("#sentiment-bars");
const x = d3.scaleLinear()
.domain([0, 10])
.range([margin.left, width - margin.right]);
const colors = ['red','grey','green'];
const y_ticks = [...Array(sentences.length).keys()];
const xAxis = g => g
.attr("transform", `translate(0,${margin.top})`)
.call(d3.axisTop(x).ticks(width / 80))
.call(g => g.select(".domain").remove());
if(method === "rect") {
const height = sentences.length * 5 + margin.top + margin.bottom;
const y = d3.scaleBand()
.domain(sentences.map((d,i) => y_ticks[i]))
.range([margin.top, height - margin.bottom])
.padding(0.1);
svg.append("g")
.selectAll("rect")
.data(sentences)
.join("rect")
.attr("x", x(0))
.attr("y", (d,i) => y(i))
.attr("fill",d => colors[d.sentiment+1])
.attr("width", d => "150")
.attr("height", y.bandwidth())
.append("title")
.text(function(d) {
return d.sentence;
});
svg.attr("width",width)
.attr("height",height);
}
else if (method === "text"){
const height = sentences.length * 12 + margin.top + margin.bottom;
const y = d3.scaleBand()
.domain(sentences.map((d,i) => y_ticks[i]))
.range([margin.top, height - margin.bottom])
.padding(0.1);
const yAxis = g => g
.attr("transform", `translate(${margin.left},0)`)
.call(d3.axisLeft(y).tickSizeOuter(0));
svg.append("g")
.style("font", "10px sans-serif")
.selectAll("text")
.data(sentences)
.join("text")
.attr("x", d => x(0)+5)
.attr("y", (d,i) => y(i) + y.bandwidth() / 2)
.attr("dy", "0.35em")
.attr("fill",d => colors[d.sentiment+1])
.text(d => d.sentence);
svg.append("g")
.call(yAxis);
svg.attr("width",width)
.attr("height",height);
}
return svg.node();
}