d3.js - how to plot one column as x axis and the other column as y axis in D3/javascripts -
i'd know how scatter plot 1 column(a) values x axis , other column(b) y axis. each row have redundant values in column different values in column b. i'd plot unique values in x axis.
e.g.
a b groupa 10 groupb 20 groupa 30 groupc 5 groupb 11
in x axis, plot group a, b, c without redundancy. in y axis, plot each values belong each group. instead of setting x axis values manually pre defining {groupa,groupb,groupc}, read observations automatically column , saves array , plot it. can me start this?
thanks,
the easiest way achieve setting 2 scales, 1 ordinal scale x axis, scalepoint
, , 1 linear scale y axis.
this x scale:
var xscale = d3.scalepoint() .domain(data.map(function(d){return d.a})) .range([50, width-50]) .padding(0.5);
and y scale:
var yscale = d3.scalelinear() .domain([0, d3.max(data, function(d){return d.b})*1.1]) .range([height - 50, 10]);
here demo:
var data = [{a: "groupa", b: 10}, {a: "groupb", b: 20}, {a: "groupa", b: 30}, {a: "groupc", b: 5}, {a: "groupb", b: 11}] var width = 400, height = 200; var svg = d3.selectall("body") .append("svg") .attr("width", width) .attr("height", height); var color = d3.scaleordinal(d3.schemecategory10) .domain(data.map(function(d){return d.a})); var xscale = d3.scalepoint() .domain(data.map(function(d){return d.a})) .range([50, width-50]) .padding(0.5); var yscale = d3.scalelinear() .domain([0, d3.max(data, function(d){return d.b})*1.1]) .range([height - 50, 10]); var circles = svg.selectall(".circles") .data(data) .enter() .append("circle") .attr("r", 8) .attr("cx", function(d){ return xscale(d.a)}) .attr("cy", function(d){ return yscale(d.b)}) .attr("fill", function(d){ return color(d.a)}); var xaxis = d3.axisbottom(xscale); var yaxis = d3.axisleft(yscale); svg.append("g").attr("transform", "translate(0,150)") .attr("class", "xaxis") .call(xaxis); svg.append("g") .attr("transform", "translate(50,0)") .attr("class", "yaxis") .call(yaxis);
<script src="https://d3js.org/d3.v4.min.js"></script>
ps: since 1 scale here ordinal (qualitative), not technically scatterplot.
Comments
Post a Comment