Public
Edited
Nov 4, 2022
1 fork
Insert cell
Insert cell
viewof csvfile = Inputs.file({label: "CSV file", accept: ".csv", required: true})
Insert cell
// data = {
// var d = d3.csvParse(await FileAttachment("google://US_youtube_trending_data_sentiment.csv").text(), d3.autoType)
// d.columns = Object.keys(d[1]);
// return d;
// }
Insert cell
data= csvfile.csv({typed: true})
Insert cell
data_title = data.filter(i=>i.view_count != 0).map(i => {const viewdata = {
categories: i.category,
net_popularity_per_view: (i.likes - i.dislikes)/i.view_count,
sentiment_scores:i["Sentiment_Scores"]
}
return viewdata})
Insert cell
Insert cell
Insert cell
// byDay = d3.rollup(data_title,
// v => Object.fromEntries(columnsToSum.map(col => [col, d3.mean(v, d => d[col])])),
// d => d.categories)
Insert cell

view_sentiment_array = Array.from((d3.rollup(data_title,
v => Object.fromEntries(columnsToSum.map(col => [col, d3.mean(v, d => d[col])])),
d => d.categories)), ([categories, counts]) => {
const result={}
result.category = categories;
result.net_popularity_per_view = (counts.net_popularity_per_view - 0.012014798319959788) / 0.06709932458
result.sentiment_scores = counts.sentiment_scores
return result;
}).sort((a, b) => d3.ascending(a.category, b.category))
Insert cell
Insert cell
// data_by_months_year= d3.rollup(data_view,
// v => Object.fromEntries(columnsToSum2.map(col => [col, d3.sum(v, d => d[col])])),
// d => d.category,d => d.published_month)
Insert cell
// data_by_days= d3.rollup(data_view,
// v => v.length,
// d => d.category,d => d.published_week)
Insert cell
Insert cell
Insert cell
Insert cell
// data_by_trend_days= d3.rollup(days_to_trend,
// v => v.length,
// d => d.category,d => d.date_range)
Insert cell
Insert cell
// Copyright 2021 Observable, Inc.
// Released under the ISC license.
// https://observablehq.com/@d3/bar-chart
function BarChart(data, {
x = (d, i) => i, // given d in data, returns the (ordinal) x-value
y = d => d, // given d in data, returns the (quantitative) y-value
title, // given d in data, returns the title text
marginTop = 20, // the top margin, in pixels
marginRight = 0, // the right margin, in pixels
marginBottom = 30, // the bottom margin, in pixels
marginLeft = 40, // the left margin, in pixels
width = 640, // the outer width of the chart, in pixels
height = 400, // the outer height of the chart, in pixels
xDomain, // an array of (ordinal) x-values
xRange = [marginLeft, width - marginRight], // [left, right]
yType = d3.scaleLinear, // y-scale type
yDomain, // [ymin, ymax]
yRange = [height - marginBottom, marginTop], // [bottom, top]
xPadding = 0.1, // amount of x-range to reserve to separate bars
yFormat, // a format specifier string for the y-axis
yLabel, // a label for the y-axis
color = "currentColor" // bar fill color
} = {}) {
// Compute values.
const X = d3.map(data, x);
const Y = d3.map(data, y);

// Compute default domains, and unique the x-domain.
if (xDomain === undefined) xDomain = X;
if (yDomain === undefined) yDomain = [0, d3.max(Y)];
xDomain = new d3.InternSet(xDomain);

// Omit any data not present in the x-domain.
const I = d3.range(X.length).filter(i => xDomain.has(X[i]));

// Construct scales, axes, and formats.
const xScale = d3.scaleBand(xDomain, xRange).padding(xPadding);
const yScale = yType(yDomain, yRange);
const xAxis = d3.axisBottom(xScale).tickSizeOuter(0);
const yAxis = d3.axisLeft(yScale).ticks(height / 40, yFormat);

// Compute titles.
if (title === undefined) {
const formatValue = yScale.tickFormat(100, yFormat);
title = i => `${X[i]}\n${formatValue(Y[i])}`;
} else {
const O = d3.map(data, d => d);
const T = title;
title = i => T(O[i], i, data);
}

const svg = d3.create("svg")
.attr("width", width)
.attr("height", height)
.attr("viewBox", [0, 0, width, height])
.attr("style", "max-width: 100%; height: auto; height: intrinsic;");

svg.append("g")
.attr("transform", `translate(${marginLeft},0)`)
.call(yAxis)
.call(g => g.select(".domain").remove())
.call(g => g.selectAll(".tick line").clone()
.attr("x2", width - marginLeft - marginRight)
.attr("stroke-opacity", 0.1))
.call(g => g.append("text")
.attr("x", -marginLeft)
.attr("y", 10)
.attr("fill", "currentColor")
.attr("text-anchor", "start")
.text(yLabel));

const bar = svg.append("g")
.attr("fill", color)
.selectAll("rect")
.data(I)
.join("rect")
.attr("x", i => xScale(X[i]))
.attr("y", i => yScale(Y[i]))
.attr("height", i => yScale(0) - yScale(Y[i]))
.attr("width", xScale.bandwidth());

if (title) bar.append("title")
.text(title);

svg.append("g")
.attr("transform", `translate(0,${height - marginBottom})`)
.call(xAxis);

return svg.node();
}
Insert cell
import {howto, altplot} from "@d3/example-components"
Insert cell
import {Legend, Swatches} from "@d3/color-legend"
Insert cell
import {howto, altplot} from "@d3/example-components"
Insert cell
chart3 = BarChart(view_sentiment_array, {
x: d => d.category,
y: d => d.net_popularity_per_view,
xDomain: view_sentiment_array.category, // sort by descending frequency
yLabel: "↑ Net Popularity per View",
width,
height: 500,
color: "steelblue"
})
Insert cell
chart4 = BarChart(view_sentiment_array, {
x: d => d.category,
y: d => d.sentiment_scores,
xDomain: view_sentiment_array.category, // sort by descending frequency
yLabel: "↑ Sentiment Scores",
width,
height: 500,
color: "steelblue"
})
Insert cell
Insert cell
chartClustered = {
const svg = d3.select(DOM.svg(width, height));
svg.append('text')
.attr('class', 'title')
.text(titleText)
.attr('y', 15)
.attr('x', width/3)
.attr('font-size', titleSize);

var bars = svg.append("g")
.selectAll("g")
.data(dataNew.dat);
bars
.join("g")
.attr("transform", d => `translate(${x0(d[groupKey])},0)`)
.selectAll("rect")
.data(d => keys.map(key => ({key, value: d[key]})))
.join("rect")
.attr("x", d => x1(d.key))
.attr("y", d => d.value ? y(d.value) : margin.top)
.attr("width", x1.bandwidth())
.attr("height", d => d.value ? y(0) - y(d.value) : height - margin.bottom - margin.top)
.attr("fill", d => d.value ? color(d.key) : 'transparent')
.on("mouseenter", function(d) {
svg.append("text").attr("class", "tool")
.attr("x", x0(d.path[1].__data__[groupKey]) + x1(d.path[0].__data__.key))
// .attr("y", y(d.path[0].__data__.value)-25)
.attr("y", margin.top - 50)
.style("display", null)
// .style("fill", color(d.path[0].__data__.key))
.style("fill", 'black')
.text("Catergory: " + d.path[0].__data__.key.charAt(0).toUpperCase() + d.path[0].__data__.key.slice(1))
.attr('font-size', tooltipSize)
svg.append("text").attr("class", "tool1")
.attr("x", x0(d.path[1].__data__[groupKey]) + x1(d.path[0].__data__.key))
// .attr("y", y(d.path[0].__data__.value)-10)
.attr("y", margin.top - 35)
.style("display", null)
// .style("fill", color(d.path[0].__data__.key))
.style("fill", 'black')
.text("Score: " + Number(d.path[0].__data__.value).toFixed(2))
.attr('font-size', tooltipSize)
})
.on("mouseout", function(d) {
svg.selectAll("text.tool").style("display", "none")
svg.selectAll("text.tool1").style("display", "none")
});

svg.append("g")
.attr("class", "x-axis")
.call(xAxis);

svg.append("g")
.call(yAxis);

svg.append("g")
.call(legend);
svg.node().scrollBy(5, 0);

return svg.node();
}
Insert cell
function zoom(svg) {
const extent = [[margin.left, margin.top], [width - margin.right, height - margin.top]];

svg.call(d3.zoom()
.scaleExtent([1, 8])
.translateExtent(extent)
.extent(extent)
.on("zoom", zoomed));

function zoomed(event) {
x0.range([margin.left, width - margin.right].map(d => event.transform.applyX(d)));
svg.selectAll("rect").data(data.dat)
.attr("x", d => x0(d[groupKey])).attr("width", x0.bandwidth())
// .attr("transform", d => `translate(${x0(d[groupKey])},0)`)
.data(d => keys.map(key => ({key, value: d[key]}))).selectAll("rect")
.attr("x", d => x1(d.key)).attr("width", x1.bandwidth());
svg.selectAll(".x-axis").call(xAxis);
}
}
Insert cell
wrap = (text) => {
const width=50
text.each(function() {
var text = d3.select(this),
words = text.text().split(/\s+/).reverse(),
word,
line = [],
lineNumber = 0,
lineHeight = 1.1, // ems
y = text.attr("y"),
dy = parseFloat(text.attr("dy")),
tspan = text.text(null).append("tspan").attr("x", 0).attr("y", y).attr("dy", dy + "em");
while (words.length >0) {
word=words.pop()
line.push(word);
tspan.text(line.join(" "));
// if (tspan.node().getComputedTextLength() > width) {
line.pop();
tspan.text(line.join(" "));
line = [word];
tspan = text.append("tspan").attr("x", 0).attr("y", y-10).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word);
// }
}
});
}
Insert cell
legend = svg => {
const g = svg
.attr("transform", `translate(${width-legendDistanceFromRight},${margin.top})`)
.attr("text-anchor", "end")
.attr("font-family", "sans-serif")
.attr("font-size", legendTextSize)
.selectAll("g")
.data(color.domain().slice().reverse())
.join("g")
.attr("transform", (d, i) => `translate(0,${i * 20})`);

g.append("rect")
.attr("x", -19)
.attr("width", 19)
.attr("height", 19)
.attr("fill", color);

g.append("text")
.attr("x", -24)
.attr("y", 9.5)
.attr("dy", "0.35em")
.text(d => d);
}
Insert cell
x0 = d3.scaleBand()
.domain(dataNew.dat.map(d => d[groupKey]))
.rangeRound([margin.left, width - margin.right])
.paddingInner(0.15)
Insert cell
x1 = d3.scaleBand()
.domain(keys)
.rangeRound([0, x0.bandwidth()])
.padding(0.05)
Insert cell
y = d3.scaleLinear()
.domain([0, d3.max(dataNew.dat, d => d3.max(keys, key => d[key]))]).nice()
.rangeRound([height - margin.bottom, margin.top])
Insert cell
legendDistanceFromRight = 20
Insert cell
color = d3.scaleOrdinal(d3.quantize(colorType, keys.length))
Insert cell
colorType = d3.interpolate("rgb(108,99,255)", "red")
Insert cell
xAxis = g => g
.attr("transform", `translate(0,${height - margin.bottom})`)
.call(d3.axisBottom(x0).tickSizeOuter(0))
.attr("font-size", xAxisFontSize)
.selectAll("text").call(wrap, x0.bandwidth())
.call(g => g.select(".domain").remove())
Insert cell
yAxis = g => g
.attr("transform", `translate(${margin.left},0)`)
.call(d3.axisLeft(y).ticks(null, "s"))
.call(g => g.select(".domain").remove())
.call(g => g.select(".tick:last-of-type text").clone()
.attr("x", -10)
.attr("y", -20)
.attr("text-anchor", "start")
.attr("font-weight", "bold")
.text(dataNew.y))
Insert cell
groupKey = dataNew.columns[0]
Insert cell
margin = ({top: 90, right: 120, bottom: 50, left: 40})
Insert cell

xAxisFontSize = 13
Insert cell
titleSize = 20
Insert cell
legendTextSize = 12
Insert cell
tooltipSize = 12
Insert cell
titleText = "Net Popularity Index vs Sentiment Score"
Insert cell
yAxisText = "Score"
Insert cell
height = 450
Insert cell
keys = Object.keys(view_sentiment_array[0]).slice(1)
Insert cell
d3 = require("d3@6")
Insert cell
dataNew = (
{
"dat": view_sentiment_array,
"columns": ["category", "net_popularity_per_view", "sentiment_scores"],
"y": yAxisText
}
)
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more