Public
Edited
Jan 1, 2023
1 star
Insert cell
Insert cell
Insert cell
Insert cell
Inputs.table(dataRename)
Insert cell
console.log(xVar)
Insert cell
console.log(yVar)
Insert cell
Type JavaScript, then Shift-Enter. Ctrl-space for more options. Arrow ↑/↓ to switch modes.

Insert cell
Insert cell
Insert cell
Insert cell
taskplot = {
const margin = ({top: 60, right: 200, bottom: 40, left: 40}); //margin object
const width = 1000; //width of SVG in pixels
const height = 600; //height of SVG in pixels

////--------------------------------- Filtering data ------------------------------------------------------------------
//filtering the data to just have rows where selected xVar and yVar exists
const data = dataRename.filter(d => d[xVar] && d[yVar])
// filtering the data to just the selected year
const filtered = data.filter(d => d.year === selectedYear)


////--------------------------------- circle scale depending on the variable population ---------------------------------
const rScale = d3.scaleSqrt()
.domain([0,d3.max(data, d => d.population)])
.range([0, 50]) //circles, la grandària en quant a rang, tenint en compte lo domini


//scale the axis depending on the information for each axis
const xScale = d3.scaleLog()//Log scales are similar to linear scales, except a logarithmic transform is applied to the input domain value before the output range value is computed.
.domain(d3.extent(data.map(d=>d[xVar]))).nice()
.range([margin.left, width - margin.right])

const yScale = d3.scaleLinear()
.domain([0,d3.max(data.map(d=>d[yVar]))]).nice()
.range([height-margin.bottom, margin.top])


////--------------------------------- Axis ------------------------------------------------------------------
//X axis based on the scale calculated before
const xAxis = g => g
.attr("transform", `translate(0,${height - margin.bottom})`)
.call(d3.axisBottom(xScale))

//Y axis based on the scale calculated before
const yAxis = g => g
.attr("transform", `translate(${margin.left},0)`)
.call(d3.axisLeft(yScale))

////--------------------------------- creating chart area ------------------------------------------------------------------
const svg = d3.create("svg")
.attr("width", width)
.attr("height", height)
.attr("viewBox",[0, 0, width, height]);

////--------------------------------- text sqaure with information ---------------------------------
const tooltip = d3.select('body')
.append('div')
.style('position', 'absolute')
.style('z-index', '1')
.style('visibility', 'hidden')
.style('padding', '10px')
.style('background', 'rgba(0,0,0,0.6)')
.style('border-radius', '4px')
.style('color', '#fff');

//creating the axis
const gx = svg.append("g")
.call(xAxis);
const gy = svg.append("g")
.call(yAxis);


////---------------------------------set color scheme ------------------------------------------------------------------
const color = d3.scaleOrdinal()
.domain(data.map(d=> d.continent))
.range(d3.schemeCategory10)
//--------------------------------- add legend: continent dots ------------------------------------------------------------------
const size = 20
const allgroups = ["Asia", "Europe", "Americas", "Africa", "Oceania"]
svg.selectAll(".legendCircles")
.data(allgroups)
.join('circle')
.attr("class","legendCircles")
.attr("cx", width-100)
.attr("cy", function(d,i){ return 280 + i*(size+5)})
.attr("r", 5)
.style("fill", function(d){ return color(d)})
//.on("mouseover", highlight)
//.on("mouseleave", noHighlight)
//Add labels beside legend dots
svg.selectAll("mylabels")
.data(allgroups)
.enter()
.append("text")
.attr("x", width -100 + size*.8)
.attr("y", function(d,i){ return 275 + i * (size + 5) + (size/2)})
.style("fill", function(d){ return color(d)})
.text(function(d){ return d})
.attr("text-anchor", "left")
.style("alignment-baseline", "middle")
.on("click", function(e,d,i) {
// reduce opacity of all groups
//d3.selectAll(".bubbles").style("opacity", .05)
// expect the one that is hovered
//d3.selectAll("."+d).style("opacity", 1)
console.log("test")
})
//.on("mouseleave", noHighlight)

//--------------------------------- Add legend: population circles ------------------------------------------------------------------
const valuesToShow = [10000000, 100000000, 1000000000]
svg.selectAll("legend")
.data(valuesToShow)
.enter()
.append("circle") // circles of the legend
.attr("cx", width - 100)
.attr("cy", function(d){ return height - 40 - rScale(d) } )
.attr("r", function(d){ return rScale(d) })
.style("fill", "none")
.attr("stroke", "black")
svg.selectAll("legend")
.data(valuesToShow)
.enter()
.append("line") //lines of the legend
.attr('x1', function(d){ return width - 60 + rScale(d) } )
.attr('x2', width -100)
.attr('y1', function(d){ return height - 40 - rScale(d) } )
.attr('y2', function(d){ return height - 40 - rScale(d) } )
.attr('stroke', 'black')
.style('stroke-dasharray', ('2,2'))
svg.selectAll("legend")
.data(valuesToShow)
.enter()
.append("text") // text of the legend
.attr('x', width - 40)
.attr('y', function(d){ return height - 40 - rScale(d) } )
.text( function(d){ return d/1000000 } )
.style("font-size", 10)
.attr('alignment-baseline', 'middle')
svg.append("text")
.attr('x', width - 60)
.attr("y", height - 20)
.text("Population (M)")
.attr("text-anchor", "middle")




//--------------------------------- legend selected ywar ------------------------------------------------------------------
svg.append("text")
.text("Year: "+selectedYear)
.attr("y", 50)
.attr("x", width-150)
.attr("font-size", 26)
.attr("font-family", "monospace")
//.attr("fill", "white");


//--------------------------------- creating the circles ------------------------------------------------------------------
// svg.selectAll('circle') // This doesn't work because of the selection
svg.selectAll('.bubbles')
.data(filtered)
.join('circle')
.attr("class", function(d) { return "bubbles" + d.continent })
.attr('cx', d => xScale(d[xVar]))
.attr('cy', d => yScale(d[yVar]))
.attr('r', d => rScale(d.population))
.style('fill', d=> color(d.continent))
.style('opacity', .6)
.style('stroke', "black")
.style('stroke-width', '1')
//interaccions en lo cursor
.on("mouseover", function(d, i) {
// change the selection style
d3.select(this)
.style('stroke-width', '4')
.style('fill', "steelblue");
const tooltipWidth = tooltip.node().offsetWidth;
const tooltipHeight = tooltip.node().offsetHeight;
tooltip
.style("left", d.pageX - tooltipWidth +'px')
.style("top", d.pageY-tooltipHeight - 10+'px') //això és per controlar lo gran que és lo requadre. Distància entre la pàgina i el ratolí
.style('visibility', 'visible') //aquí el fem visible, en lo fromat que li hem dit abans
.html(`<b>Country</b>: ${i.country} <br/>
<b>${[yVar]}</b>: ${i[yVar].toLocaleString()} <br />
<b>${[xVar]}</b>: ${i[xVar].toLocaleString()}`);
})
.on("mouseout", function(d,i) {
d3.select(this)
.style('fill', d=> color(d.continent))
.style('stroke-width', '1')
tooltip.style('visibility', 'hidden')
})


// What to do when one group is hovered
const highlight = function(d){
// reduce opacity of all groups
d3.selectAll(".bubbles").style("opacity", .05)
// expect the one that is hovered
d3.selectAll("."+d).style("opacity", 1)
}

// And when it is not hovered anymore
const noHighlight = function(d){
d3.selectAll(".bubbles").style("opacity", 1)
}
return svg.node();
}

Insert cell
Insert cell
filteredDataLine = dataRename.filter(d => d[yVarLine])
Insert cell
grouped = d3.groups(filteredDataLine, d => d.country)
Insert cell
countryNames = grouped.map(d => d[0])
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
countries = [
"Argentina",
"Switzerland",
"India",
"China",
"United States",
];
Insert cell
filteredLine = data.filter(d => countries.includes(d.country_name))
Insert cell
Plot.plot({
facet:{
data:filteredLine,
x: "country_name"
},
marks: [
Plot.line(filteredLine, {
x: "year",
y: "PIG",
}),
Plot.line(filteredLine, {
x: "year",
y: "POULTRY",
}),
Plot.line(filteredLine, {
x: "year",
y: "BEEF",
}),
Plot.line(filteredLine, {
x: "year",
y: "SHEEP",
}),

]
})
Insert cell
Insert cell
Insert cell
total_meat_2018 = diff_total_meat.filter (d => d.year==2018)
.filter (g => g.agriculture_meat_consumption)
Insert cell
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