Interactive bar chart domain issue - javascript

I'm trying to create an interactive bar chart of the top Forbes 100 companies, with buttons to change between sales and profit.
The first issue I'm having is with the domain:
x.domain([0, d3.max(data, d => d[xValue])])
Error says "data not defined"
but I defined it here:
d3.csv("data/data_clean.csv").then(data => {
data.forEach(d => {
d.sales_usd_billion = Number(d.sales_usd_billion)
d.profit_usd_billion = Number(d.profit_usd_billion)
})
data snapshot:
rank,company,country,sales_usd_billion,sales_unit,profit_usd_billion,profit_unit,assets_usd_billion,market_usd_billion,sales_usd,profit_usd,assets_usd
1,Berkshire Hathaway,United States,276.09,B,89.8,B,958.78,741.48,276.09,89.8,958.78
2,ICBC,China,208.13,B,54.03,B,5518.51,214.43,208.13,54.03,5518.51
3,Saudi Arabian Oil Company (Saudi Aramco),Saudi Arabia,400.38,B,105.36,B,576.04,2292.08,400.38,105.36,576.04
4,JPMorgan Chase,United States,124.54,B,42.12,B,3954.69,374.45,124.54,42.12,3954.69
5,China Construction Bank,China,202.07,B,46.89,B,4746.95,181.32,202.07,46.89,4746.95
6,Amazon,United States,469.82,B,33.36,B,420.55,1468.4,469.82,33.36,420.55
7,Apple,United States,378.7,B,100.56,B,381.19,2640.32,378.7,100.56,381.19
8,Agricultural Bank of China,China,181.42,B,37.38,B,4561.05,133.38,181.42,37.38,4561.05
9,Bank of America,United States,96.83,B,31,B,3238.22,303.1,96.83,31,3238.22
10,Toyota Motor,Japan,281.75,B,28.15,B,552.46,237.73,281.75,28.15,552.46
11,Alphabet,United States,257.49,B,76.03,B,359.27,1581.72,257.49,76.03,359.27
12,Microsoft,United States,184.9,B,71.19,B,340.39,2054.37,184.9,71.19,340.39
13,Bank of China,China,152.43,B,33.57,B,4192.84,117.83,152.43,33.57,4192.84
14,Samsung Group,South Korea,244.16,B,34.27,B,358.88,367.26,244.16,34.27,358.88
FULL CODE:
//Forbes companies bar chart
//set up chart area
const MARGIN = { LEFT: 250, RIGHT: 10, TOP: 50, BOTTOM: 100 }
const WIDTH = 1000 - MARGIN.LEFT - MARGIN.RIGHT
const HEIGHT = 1100 - MARGIN.TOP - MARGIN.BOTTOM
const svg = d3.select("#chart-area").append("svg")
.attr("width", WIDTH + MARGIN.LEFT + MARGIN.RIGHT)
.attr("height", HEIGHT + MARGIN.TOP + MARGIN.BOTTOM)
const g = svg.append("g")
.attr("transform", `translate(${MARGIN.LEFT}, ${MARGIN.TOP})`)
// X label
g.append("text")
.attr("class", "x axis-label")
.attr("x", WIDTH / 2)
.attr("y", HEIGHT + 50)
.attr("font-size", "20px")
.attr("text-anchor", "middle")
// Y label
const yLabel = g.append("text")
.attr("class", "y axis-label")
.attr("x", - (HEIGHT / 2))
.attr("y", -200)
.attr("font-size", "20px")
.attr("text-anchor", "middle")
.attr("transform", "rotate(-90)")
.text("Company")
//scales
const x = d3.scaleLinear()
.range([0, WIDTH])
const y = d3.scaleBand()
.range([HEIGHT, 0])
//axis generators
const xAxisCall = d3.axisBottom()
const yAxisCall = d3.axisLeft()
//axis groups
const xAxisGroup = g.append("g")
.attr("class", "x axis")
.attr("transform", `translate(0, ${HEIGHT})`)
const yAxisGroup = g.append("g")
.attr("class", "y axis")
//event listeners
$("#var-select").on("change", update)
d3.csv("data/data_clean.csv").then(data => {
data.forEach(d => {
d.sales_usd_billion = Number(d.sales_usd_billion)
d.profit_usd_billion = Number(d.profit_usd_billion)
})
update()
})
function update() {
const t = d3.transition().duration(750)
//filter based on selections
const xValue = $("#var-select").val()
x.domain([0, d3.max(data, d => d[xValue])])
y.domain(data.map(d => d.company))
data.sort(function(a, b) {
return b.rank - a.rank;
})
//update axes
xAxisCall.scale(x)
xAxis.transition(t).call(xAxisCall)
yAxisCall.scale(y)
yAxis.transition(t).call(yAxisCall)
//***Tooltips */
//*** --- */
rects.enter().append("rect")
.attr("y", d => y(d.company) +3)
.attr("x", 0)
.attr("width", d => x(d[value]))
.attr("height", d => 4)

You need to pass data in your update method and change function definition as function update(data). Its a simple scope problem, I would suggest that try debugging the code and then ask for help here.To learn more about debugging, follow a javascript debugging tutorial

Related

d3.js Bar Chart - Y Axis NaN

Getting NaN on the Y axis for a d3.js bar chart.
Question relates to this one .
The answer in that question has static data, which is identical to the Ajax JSON. See commented line for const data But the Ajax data is not working.
The data is loaded but the column with data has no height as there is no Y scale data.
Console log:
Error: <rect> attribute y: Expected length, "NaN".
Error: <rect> attribute height: Expected length, "NaN".
Error: <text> attribute y: Expected length, "NaN".
Chart with Ajax loaded data:
var margin = {top: 50, right: 135, bottom: 70, left: 80},
width = 1050 - margin.left - margin.right,
height = 540 - margin.top - margin.bottom;
var svg = d3.select("#domains")
.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 + ")");
//const data = [{"Domain":"Knowledge","Knowledge":0},{"Domain":"Problem Solving","problem_solving":0},{"Domain":"Skill","skill":0},{"Domain":"Transferable","transferable":100}];
d3.json("json/domains.json", function(error, data) {
const normalized = data.map(item => {
const name = item['Domain'];
const attr = name.toLowerCase().replace(' ', '_');
const value = item[attr];
return {name, value};
});
console.log('N: ', normalized);
/*
// Transpose the data into layers
var dataset = d3.layout.stack()(["Knowledge", "Problem Solving, Skill, Transferable"].map(function(lvl) {
return data.map(function(d) {
return {
x: d.Domain,
y: d[lvl]
};
});
}));
var disciplines = d3.nest()
.key(function(d){return d.Domain})
.rollup(function(leaves){
return d3.sum(leaves, function(d) {return d3.sum(d3.values(d))});
})
.entries(data);
*/
// Set x, y and colors
var x = d3.scale.ordinal()
.domain(normalized.map(item => item.name))
.rangeRoundBands([10, width-10], 0.35, 0);
const maxValue = normalized.reduce((max, item) => Math.max(max, item.value), 0);
var y = d3.scale.linear()
.domain([0, maxValue])
.range([height, 0]);
var colors = ["#83d1c4", "#f17950", "#838BD1", "#F150BE"];
// Define and draw axes
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.ticks(5)
.tickSize(-width, 0, 0)
.tickFormat(function(d) {
return d;
});
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.outerTickSize(0)
d3.select('.y axis .tick:first-child').remove();
/*
var tip = d3.tip()
.attr('class', 'd3-tip')
.offset([-0, 0])
.html(function(d) {
return d.y + '%';
})
svg.call(tip);
*/
svg.append("g")
.attr("class", "y axis")
.attr("transform", "translate(0,0)")
.call(yAxis);
svg.append("g")
.call(xAxis)
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("text")
.attr("x", 390 )
.attr("y", 480 )
.style("text-anchor", "middle")
.text("Domains");
svg.append("text")
.attr("x", -200 )
.attr("y", -40 )
.attr("transform", "rotate(-90)" )
.attr('style', 'font-size:12px')
.style("text-anchor", "middle")
.text("Percentage of Learning Events");
// Create groups for each series, rects for each segment
var groups = svg.selectAll("g.group")
.data(normalized)
.enter().append("g")
.attr("class", "group")
.style("fill", function(d, i) { return colors[i]; });
groups.append("rect")
.attr("y", function(d) { return y(d.value); })
.attr("x", d => x(d.name))
.attr("height", function(d) { return y(0) - y(d.value); })
.attr('class', 'segment')
.attr("width", x.rangeBand())
// .on('mouseover', tip.show)
// .on('mouseout', tip.hide);
columns = svg.append("g")
.selectAll("text")
.data(normalized)
.enter().append("text")
.attr("x", function(d){
return x(d.name) + x.rangeBand()/2
})
.attr("y", function (d) {
return y(d.value);
})
.attr("dy", "-0.7em")
.attr('style', 'font-size:11px')
.text( function (d){
return d3.format(".2f")(d.value) + '%';
})
.style({fill: 'black', "text-anchor": "middle"});
});
Chart with static data:
Although your dataset had an typo, which can break your current setup if you had the same in the json output. We can not be that sure if there is no data provided in example from actual json response, which can be different than what's in your const data example
const data = [{"Domain":"Knowledge","Knowledge":0},{"Domain":"Problem Solving","problem_solving":0},{"Domain":"Skill","skill":0},{"Domain":"Transferable","transferable":100}];
Try with lowercase "knowledge":0 which was printing the chart correctly on my screen
https://jsfiddle.net/978ync63/

How to structure Vue for Interactive D3 Chart

In this Vue component, am trying to create an interactive bar chart hover is seems to be recreating the group element every time the data is updated. If someone can tell me where the problem is because am stuck since I've tried both the general update pattern as well as nest updated pattern.
export default {
name: "StatisticsUI",
props:["reps"],
mounted(){
this.setOptions(),
this.genChart()
},
updated(){
this.genChart()
},
methods:{
......
genChart(){
const data = [
["CCP",2],
["ZPA",1],
["ERA",3],
["POS",4],
]
const svg = d3.select("svg")
const width = svg.attr("width")
const height = svg.attr("height")
const margin ={left: 50, right:50, top:50, bottom:50}
const innerWidth = width - margin.left - margin.right
const innerHeight = height - margin.top - margin.bottom
const g = svg.append("g")
.attr("transform", `translate(${margin.left}, ${margin.top})`);
const yAxis = g.append("g").attr("class", "y-axis")
const xAxis = g.append("g").attr("class", "x-axis")
const xValue = d => d[0]
const yValue = d => d[1]
const xScale = d3.scaleBand().domain(data.map(xValue)).range([0, innerWidth]).padding(0.2);
const yScale = d3.scaleLinear().domain([0, d3.max(data, yValue)]).range([innerHeight, 0]);
yAxis.call(d3.axisLeft(yScale));
xAxis
.call(d3.axisBottom(xScale))
.attr("transform", `translate(0, ${innerHeight})`)
let rect = g.selectAll("rect").data(data);
rect.exit().remove()
rect
.enter()
.append("rect")
.merge(rect)
.attr("fill", "#69b3a2")
.attr("x", (d) => xScale(xValue(d)))
.attr("width", xScale.bandwidth())
.attr("height", 0)
.attr("y", innerHeight)
.transition()
.duration(1000)
.delay((d, i) => i * 50)
.ease(d3.easeBounce)
.attr("y", (d) => yScale(yValue(d)))
.attr("height", function (d) {
return innerHeight - yScale(yValue(d));
});
}
}
}

Can not show labels in group bar chart d3js v6

I try to follow as following link to put labels in the groups bar chart, but it does not show up.
Anyone know what's going on my text label?
http://plnkr.co/edit/9lAiAXwet1bCOYL58lWN?p=preview&preview
Append text to Grouped Bar Chart in d3js v4
// set the dimensions and margins of the graph
var margin = { top: 10, right: 30, bottom: 40, left: 50 },
width = 700 - margin.left - margin.right,
height = 400 - margin.top - margin.bottom;
const dataUrl = "https://raw.githubusercontent.com/yushinglui/IV/main/time_distance_status_v2.csv"
//fetch the data
d3.csv(dataUrl)
.then((data) => {
// append the svg object to the body of the page
var svg = d3.select("#graph-2")
.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 + ")")
// List of subgroups = header of the csv files = soil condition here
var subgroups = data.columns.slice(1)
// List of groups = species here = value of the first column called group -> I show them on the X axis
var groups = d3.map(data, function (d) { return (d.startTime) })
// Add X axis
var x = d3.scaleBand()
.domain(groups)
.range([0, width])
.padding([0.2])
svg.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x).tickSize(0));
// Add Y axis
var y = d3.scaleLinear()
.domain([0, 20])
.range([height, 0]);
svg.append("g")
.call(d3.axisLeft(y));
// Another scale for subgroup position?
var xSubgroup = d3.scaleBand()
.domain(subgroups)
.range([0, x.bandwidth()])
.padding([0.05])
// color palette = one color per subgroup
var color = d3.scaleOrdinal()
.domain(subgroups)
.range(['#98abc5', '#8a89a6'])
// Show the bars
svg.append("g")
.selectAll("g")
// Enter in data = loop group per group
.data(data)
.enter()
.append("g")
.attr("transform", function (d) { return "translate(" + x(d.startTime) + ",0)"; })
.selectAll("rect")
.data(function (d) { return subgroups.map(function (key) { return { key: key, value: d[key] }; }); })
.enter()
.append("rect")
.attr("x", function (d) { return xSubgroup(d.key); })
.attr("y", function (d) { return y(d.value); })
.attr("width", xSubgroup.bandwidth())
.attr("height", function (d) { return height - y(d.value); })
.attr("fill", function (d) { return color(d.key); })
//axis labels
svg.append('text')
.attr('x', - (height / 2))
.attr('y', width - 650)
.attr('transform', 'rotate(-90)')
.attr('text-anchor', 'middle')
.style("font-size", "17px")
.text('Average Distance');
svg.append('text')
.attr('x', 300)
.attr('y', width - 240)
.attr('transform', 'rotate()')
.attr('text-anchor', 'middle')
.style("font-size", "17px")
.text('Start Time');
// legend
svg.append("circle").attr("cx", 200).attr("cy", 20).attr("r", 6).style("fill", "#98abc5")
svg.append("circle").attr("cx", 300).attr("cy", 20).attr("r", 6).style("fill", "#8a89a6")
svg.append("text").attr("x", 220).attr("y", 20).text("Present").style("font-size", "15px").attr("alignment-baseline", "middle")
svg.append("text").attr("x", 320).attr("y", 20).text("Absent").style("font-size", "15px").attr("alignment-baseline", "middle")
//text labels on bars
svg.append("g")
.selectAll("g")
// Enter in data = loop group per group
.data(data)
.enter()
.append("g")
.attr("transform", function (d) { return "translate(" + x(d.startTime) + ",0)"; })
.selectAll("text")
.data(function (d) {
return [d['P'], d['ABS']];
})
.enter()
.append("text")
.attr("fill", "black")
.text(function (d) {
return formatCount(d)
})
.attr("transform", function (d, i) {
var x0 = xSubgroup.bandwidth() * i + 11,
y0 = y(d) + 8;
return "translate(" + x0 + "," + y0 + ") rotate(90)";
})
});
try this...and if possible please provide code snippet....
svg.append("text")
.attr("fill", "black")
.text(function (d) {
console.log( formatCount(d) )
return formatCount(d)
})
.attr("transform", function (d, i) {
var x0 = xSubgroup.bandwidth() * i + 11,
y0 = y(d) + 8;
return "translate(" + x0 + "," + y0 + ") rotate(90)";
})

render bar charts in javascript using svg and 2D array from json

Have spent the last 2 days looking through stackoverflow and online examples as to why my charts aren't displaying properly.
I'm sure I'm missing something in terms of the scaling portion of the code. If I copy the dark part at the bottom of the x-Axis on the chart to notepad it gives me all of the x-axis elements.
Can anyone point me in the right direction?
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.8.0/d3.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded',function(){
req.open("GET",'https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/GDP-data.json',true);
req.send();
req.onload=function(){
json=JSON.parse(req.responseText);
document.getElementsByClassName('title')[0].innerHTML=json.name;
dataset=json.data;
const w = 500;
const h = 300;
const padding = 10;
// create an array with all date names
const dates = dataset.map(function(d) {
return d[0];
});
const xScale = d3.scaleBand()
.rangeRound([padding, w-padding])
.padding([.02])
.domain(dates);
console.log("Scale Bandwidth: " + xScale.bandwidth());
const yScale = d3.scaleLinear()
.rangeRound([h-padding, padding])
.domain(0,d3.max(dataset, (d)=>d[1]));
console.log("Dataset Max Height: " + d3.max(dataset, (d)=>d[1]));
const xAxis = d3.axisBottom(xScale);
const yAxis = d3.axisLeft(yScale);
const svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
svg.append("g")
.attr("transform", "translate(0," + (h - padding) + ")")
.call(xAxis);
svg.append("g")
.attr("transform", "translate(" + padding + ",0)")
.call(yAxis);
svg.selectAll("rect")
.data(dataset)
.enter()
.append("rect")
.attr("width",(d,i)=>xScale.bandwidth())
.attr("height",(d,i)=>(h-yScale(d[1])))
.attr("x", (d,i)=>xScale(d[0]))
.attr("y", (d,i)=>yScale(d[1]))
.attr("fill", "navy")
.attr("class", "bar");
};
});
</script>
<h1 class="title">Title Will Go Here</h1>
</body>
D3 now uses Promises instead of asynchronous callbacks to load data. Promises simplify the structure of asynchronous code, especially in modern browsers that support async and await.
Changes in D3 5.0
Also, you are right in that your yScale is broken. Linear scales need a range and a domain, each being passed a 2 value array.
const yScale = d3.scaleLinear()
.range([h - padding, padding])
.domain([0, d3.max(dataset, (d) => d[1])]);
document.addEventListener('DOMContentLoaded', async function() {
const res = await d3.json("https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/GDP-data.json");
//console.log(res.data)
const dataset = res.data
const w = 500;
const h = 300;
const padding = 10;
// create an array with all date names
const dates = dataset.map(function(d) {
return d[0];
});
const max = d3.max(dataset, function(d) { return d[1]} )
const xScale = d3.scaleBand()
.rangeRound([0, w])
.padding([.02])
.domain(dates);
console.log("Scale Bandwidth: " + xScale.bandwidth());
const yScale = d3.scaleLinear()
.range([h - padding, padding])
.domain([0, d3.max(dataset, (d) => d[1])]);
console.log("Dataset Max Height: " + d3.max(dataset, (d) => d[1]));
const xAxis = d3.axisBottom(xScale);
const yAxis = d3.axisLeft(yScale);
const svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
svg.append("g")
.attr("transform", "translate(0," + (h - padding) + ")")
.call(xAxis);
svg.append("g")
.attr("transform", "translate(" + padding + ",0)")
.call(yAxis);
svg.selectAll("rect")
.data(dataset)
.enter()
.append("rect")
.attr("width", (d, i) => xScale.bandwidth())
.attr("height", (d, i) => (h - yScale(d[1])) )
.attr("x", (d, i) => xScale(d[0]))
.attr("y", (d, i) => yScale(d[1]))
.attr("fill", "navy")
.attr("class", "bar");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.8.0/d3.min.js"></script>
Codepen

Updating d3 scatterplot, new data points are not in the correct positions

Spent hours on this and still not really sure whats going wrong.
My plot is supposed to update based on a bunch of parameters the user selects. When the plot needs to add new data points the new points are not displayed correctly on the plot.
Check out the new plot:
With these parameters all the circles should be in a line. While the original "line" is in the correct location the new "line" does not match up with the grid.
Here is the function to make a new plot. This works fine, all the data points are where they should be.
export const newPlot = (Params) => {
d3.selectAll("svg").remove();
let margin = {top: 50, right: 20, bottom: 30, left: 40},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
let x = d3.scaleLinear().range([0, width]);
let y = d3.scaleLinear().range([height, 0]);
let svg = d3.select('.plot').append("svg")
.attr('class', 'svgPlot')
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform","translate(" + margin.left + "," + margin.top + ")");
d3.json(`../assets/data/${Params.type}${Params.Year}.json`, (error, data) => {
if (error) throw error;
const refinedData = parametrize(data, Params);
refinedData.forEach((d) => {
d[Params.xSelect] = Number(d[Params.xSelect]);
d[Params.ySelect] = Number(d[Params.ySelect]);
});
let min = d3.min(refinedData,(d) => d[Params.xSelect]);
x.domain([(min - 2 <= 0 ? 0 : min - 2),
d3.max(refinedData,(d) => d[Params.xSelect])]);
y.domain([0, d3.max(refinedData,(d) => d[Params.ySelect])]);
svg.selectAll("circles")
.data(refinedData)
.enter().append("circle")
.attr('id', (d) => `${d.Player}`)
.attr("r", 5)
.attr("cx", (d) => x((d[Params.xSelect])) )
.attr("cy", (d) => y((d[Params.ySelect])) );
svg.append("g")
.attr("class", "x-axis")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));
svg.append("g")
.attr("class", "y-axis")
.call(d3.axisLeft(y));
svg.append('text')
.attr("class", "label")
.attr('id', 'xlabel')
.attr("transform","translate(" + (width - 20) + " ," + (height-5) + ")")
.style("fill", "white")
.style("text-anchor", "middle")
.text(`${Params.xSelect}`);
svg.append('text')
.attr("class", "label")
.attr('id', 'ylabel')
.attr("transform", "rotate(-90)")
.attr("y", 1)
.attr("x", (height/2 - 250))
.attr("dy", "1em")
.style("font-family", "sans-serif")
.style("fill", "white")
.style("text-anchor", "middle")
.text(`${Params.ySelect}`);
});
};
Here is the update function. Circles that are added are not in the correct location and are all offset by the same amount.
export const rePlot = (Params) => {
let margin = {top: 50, right: 20, bottom: 30, left: 40},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
let xUp = d3.scaleLinear().range([0, width]);
let yUp = d3.scaleLinear().range([height, 0]);
let tooltip = d3.select("body").append("div")
.attr("class", "toolTip")
.style("display", "none");
let svg = d3.select('.svgPlot');
d3.json(`../assets/data/${Params.type}${Params.Year}.json`, (error, data) => {
if (error) throw error;
const refinedData = parametrize(data, Params);
refinedData.forEach((d) => {
d[Params.xSelect] = Number(d[Params.xSelect]);
d[Params.ySelect] = Number(d[Params.ySelect]);
});
let min = d3.min(refinedData,(d) => d[Params.xSelect]);
xUp.domain([(min - 2 <= 0 ? 0 : min - 2),
d3.max(refinedData,(d) => d[Params.xSelect])]);
yUp.domain([0, d3.max(refinedData,(d) => d[Params.ySelect])]);
svg.select('.x-axis')
.transition()
.duration(1000)
.call(d3.axisBottom(xUp));
svg.select('.y-axis')
.transition()
.duration(1000)
.call(d3.axisLeft(yUp));
svg.select('#xlabel')
.text(`${Params.xSelect}`);
svg.select('#ylabel')
.text(`${Params.ySelect}`);
let circle = svg.selectAll("circle")
.data(refinedData);
circle.exit()
.transition()
.remove();
circle.transition()
.duration(1000)
.attr("r", 5)
.attr("cx", (d) => xUp((d[Params.xSelect])) )
.attr("cy", (d) => yUp((d[Params.ySelect])) );
circle.enter().append("circle")
.attr('id', (d) => `${d.Player}`)
.attr("r", 5)
.attr("cx", (d) => xUp((d[Params.xSelect])) )
.attr("cy", (d) => yUp((d[Params.ySelect])) );
});
}
Your first set of circles gets appended to a group that is translated:
let svg = d3.select('.plot').append("svg")
.attr('class', 'svgPlot')
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform","translate(" + margin.left + "," + margin.top + ")");
In this case, the svg variable refers to a translated group. However, when you later reselect, you actually append to the root SVG element:
let svg = d3.select('.svgPlot');
This is the origin of the difference.

Categories

Resources