D3Js similar labels/duplicates use the to same x value - html

I'm using the following code. The issue is if my labels have the same value the values join themselves to the existing x value label.
output = [
{ day : "M", frequency : 1},
{ day : "M", frequency : 2}
{ day : "T", frequency : 3}
{ day : "T", frequency : 4}
{ day : "M", frequency : 5}
]
var margin = {top: 10, right: 10, bottom: 30, left: 10},
width = $('#dayhour').width() - margin.left - margin.right,
height = 240 - margin.top - margin.bottom;
var xValue = function(d) { return d.day; }, // data -> value
xScale = d3.scale.ordinal().rangeRoundBands([0, width], .1), // value -> display
xMap = function(d) { return xScale(xValue(d)); }, // data -> display
xAxis = d3.svg.axis().scale(xScale).orient("bottom");
var yValue = function(d) { return d.frequency; }, // data -> value
yScale = d3.scale.linear().range([height, 0]), // value -> display
yMap = function(d) { return yScale(yValue(d)); }, // data -> display
yAxis = d3.svg.axis().scale(yScale).orient("left");
var svg = d3.select("body").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 + ")");
xScale.domain(output.map(xValue));
yScale.domain([0, d3.max(output, yValue)]);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.selectAll(".bar")
.data(output)
.enter().append("rect")
.attr("class", "bar")
.attr("x", xMap)
.style("stroke", '#A1B9CC')
.style("stroke-width", '1')
.style("fill", "#CFDCE5")
.attr("width", xScale.rangeBand)
.attr("y", yMap)
.attr("height", function(d) { return height - yMap(d); });
After reading a couple of answers I tried changing the xMap function to this but it didn't really help.
xMap = function(d,i) { console.log(i); return i * xScale(xValue(d)); }
I'm sure the fix to this is something minor but I just want to display the output as bars in the same order as the array & not have the same bars using the same x axis position if the day value is a duplicate.
If possible could the individual change be pointed out so that others can also benefit from this?
There are a lot of posts on this but they are not very helpful because they are so localized.

In your code, you're using D3's scales to determine where bars are created. Scales map input to output values, i.e. the same input value will be mapped to the same output value. To get different outputs, you have to provide different inputs. That is, your code is fine, but the data needs to be changed/amended. You could for example add another attribute:
output = [
{ day : "M", frequency : 1, ID: "1"},
{ day : "M", frequency : 2, ID: "2"}
{ day : "T", frequency : 3, ID: "3"}
{ day : "T", frequency : 4, ID: "4"}
{ day : "M", frequency : 5, ID: "5"}
]
// more code
var xValue = function(d) { return d.ID; },
The rest of the code can remain as is.

Related

adding mouseover event to d3.js bar chart [duplicate]

This question already has an answer here:
D3: .transition() not working with events
(1 answer)
Closed 2 years ago.
So I have a bar chart with buttons that will update preset input data and now I want to include tooltip so that it will show data from y-axis when hovered. I tried to follow some tutorials that I could find but still failed. Below is what I've done so far but I took out most of the data to avoid confusion.
I got unknown type:mouseover for the following code
var AU = [
{group: "NSW", value: 871.8},
{group: "VIC", value: 736.8},
{group: "QLD", value: 517.9},
{group: "SA", value: 460.1},
{group: "WA", value: 498.5},
{group: "TAS", value: 451.4},
{group: "NT", value: 410.1},
{group: "ACT", value: 699.1},
{group: "Australia", value: 678.5}
];
// set the dimensions and margins of the graph
var margin = {top: 30, right: 30, bottom: 70, left: 60},
width = 600 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
// append the svg object to the body of the page
var svg = d3.select("#my_dataviz")
.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 + ")");
// Initialize the X axis
var x = d3.scaleBand().range([ 0, width ])
.paddingInner(0.2);
var xAxis = svg.append("g")
.attr("transform", "translate(0," + height + ")")
// Initialize the Y axis
var y = d3.scaleLinear()
.range([ height, 0]);
var yAxis = svg.append("g")
.attr("class", "myYaxis")
// A function that create / update the plot for a given variable:
function update(data) {
// Update the X axis
x.domain(data.map(function(d) { return d.group; }))
xAxis.call(d3.axisBottom(x))
// text label for the x axis
// text label for the x axis
svg.append("text")
.attr("transform",
"translate(" + (width/2) + " ," +
(height + margin.top + 20) + ")")
.style("text-anchor", "middle")
.text("Postcode");
// Update the Y axis
y.domain([0, d3.max(data, function(d) { return d.value }) ]);
yAxis.transition().duration(1000).call(d3.axisLeft(y));
svg.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 0 - margin.left)
.attr("x",0 - (height / 2))
.attr("dy", "1em")
.style("text-anchor", "middle")
.text("Price ('000k)");
// Create the u variable
var u = svg.selectAll("rect")
.data(data)
u
.enter()
.append("rect") // Add a new rect for each new elements
.merge(u) // get the already existing elements as well
.transition() // and apply changes to all of them
.duration(1000)
.attr("x", function(d) { return x(d.group); })
.attr("y", function(d) { return y(d.value); })
.attr("width", x.bandwidth())
.attr("height", function(d) { return height - y(d.value); })
.attr("fill", "#69b3a2")
.on("mouseover", function(d){tooltip.text(d); return tooltip.style("visibility", "visible");})
.on("mousemove", function(){return tooltip.style("top", (d3.event.pageY-10)+"px").style("left",(d3.event.pageX+10)+"px");})
.on("mouseout", function(){return tooltip.style("visibility", "hidden");});
// If less group in the new dataset, I delete the ones not in use anymore
u
.exit()
.remove()
}
// Initialize the plot with the first dataset
update(AU)
The reason for this error is that by calling .transition(), the selected element changes from the result of d3.select to the currently active transition. And while transition.on supports events ("start", "end", "interrupt"), it does not support "mouseover". You can fix this by moving the .on() to before your call to .transition(). I've illustrated below how this error occurs.
const svg = d3.select("body")
.append("svg");
svg
.append("rect")
.attr("width", 100)
.attr("height", 100)
.attr("fill", "blue")
.on("mouseover", function() { d3.select(this).attr("fill", "red"); });
svg
.append("rect")
.attr("x", 100)
.attr("width", 100)
.attr("height", 100)
.attr("fill", "white")
.transition()
.duration(500)
.attr("fill", "green")
.on("mouseover", function() { d3.select(this).attr("fill", "red"); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.min.js"></script>

d3.tree get min & max value

I want to get the min and max value of the "size" attributes(the json structure for tree includes three attributes: name, size and children)
But I cannot get the right value. Though in the json file, the max value is 100, the min value is 5, the result I get is 94 and 100. And the most strange thing is that when I change the maximum size "100" to "99", the max and min value changes to 99 and 11. What is the problem?
here is the html file:
<!DOCTYPE html>
<meta charset="utf-8">
<body>
<script src="//d3js.org/d3.v3.min.js"></script>
<script>
var margin = {top: 20, right: 120, bottom: 20, left: 120}, width = 1500 - margin.right - margin.left, height = 500 - margin.top - margin.bottom;
var i = 0, duration = 750, root;
var tree = d3.layout.tree() .size([height, width]) .value(function(d) { return d.size;});
var svg = d3.select("body").append("svg")
.attr("width", width + margin.right + margin.left)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
d3.json("./parse_tree.json", function(error, parse_tree) {
root = parse_tree;
root.x0 = height / 2;
root.y0 = 0;
update(root);
});
function update(source1) {
var originalConsole = console;
var nodes = tree.nodes(root).reverse(),
links = tree.links(nodes);
var node = svg.selectAll("g.node")
.data(nodes, function(d) { return d.id || (d.id = ++i); });
var t_max = d3.max(nodes, function(d) { return d.size;})
var t_min = d3.min(nodes, function(d) { return d.size;});
originalConsole.log(t_max);
originalConsole.log(t_min);
}
</script>
Here is the json file:
{
"name":"para",
"size":"11",
"children":[
{
"name":"top",
"size":"32",
"children":[
{"name":"S",
"size":"13",
"children": [
{"name":"NP",
"size":"5",
"children":[
{"name":"PRP",
"size":"89",
"children":[{"name":"You","size":"88"}]
}
]
},
{"name":"VP",
"size":"89",
"children": [
{"name":"VBP",
"size":"15",
"children":[{"name":"are", "size":"38"}]
},
{"name":"NP",
"size":"83",
"children": [
{"name":"DT",
"size":"29",
"children":[{"name":"a", "size":"53"}]
},
{"name":"NN",
"size":"50",
"children":[{"name":"boy", "size":"99"}]
}
]
}
]
},
{"name":".",
"size":"94",
"children":[{"name":".", "size": "67"}]
}
]
}
]
}
]
}
The size in the JSON object is a string, thus things turn out "not quite like expected".
So, to fix it, you have to change type to int, which is "luckily" pretty direct in JS:
var t_max = d3.max(nodes, function(d) {
return +d.size;
})
var t_min = d3.min(nodes, function(d) {
return +d.size;
});
... or somewhere else in the script.
Oh, and by the way, try this:
console.log(d3.extent(nodes, function(d) { return +d.size;})); // [5, 99]

d3js json pie chart

I am trying to create a piechart for some data I have in a JSON file, however I keep getting an error and I am not sure why.
My JSON file is like this:
{"data":[
{"ap": [
{"floorratio": [
{"floor":"Basement", "ratio": 0.20},
{"floor":"Ground", "ratio": 0.20},
{"floor":"First Floor", "ratio": 0.15},
{"floor":"Second Floor", "ratio": 0.20},
{"floor":"Third Floor", "ratio": 0.25}
]}
]},
{"ap": [
{"floorratio": [
{"floor":"Basement", "ratio": 0.10},
{"floor":"Ground", "ratio": 0.30},
{"floor":"First Floor", "ratio": 0.10},
{"floor":"Second Floor", "ratio": 0.15},
{"floor":"Third Floor", "ratio": 0.35}
]}
]}
]}
and my HTML code is:
<!doctype html>
<html>
<head>
<title>Pie Chart Test</title>
<script src="d3.min.js"></script>
</head>
<style>
body {
font: 10px sans-serif;
}
.arc path {
stroke: #fff;
}
</style>
<body>
<script>
var width = 960,
height = 500,
radius = Math.min(width, height) / 2;
var color = d3.scale.ordinal()
.range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]);
var arc = d3.svg.arc()
.outerRadius(radius - 10)
.innerRadius(0);
var pie = d3.layout.pie()
.sort(null)
.value(function (d) {
return d.data[0].ap[0].floorratio[0].ratio;
});
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
d3.json("APCategories.json", function (data) {
var g = svg.selectAll(".arc")
.data(pie(function (d) { return d.data[0].ap[0].floorratio[0]}))
.enter().append("g")
.attr("class", "arc");
g.append("path")
.attr("d", arc)
.style("fill", function (d) {
return color[d.data[0].ap[0].floorratio[0].floor];
});
g.append("text")
.attr("transform", function (d) {
return "translate(" + arc.centroid(d) + ")";
})
.attr("dy", ".35em")
.style("text-anchor", "middle")
.text(function (d) {
return d.data[0].ap[0].floorratio[0].floor;
});
});
</script>
</body>
</html>
I keep getting the error when I inspect the element that i.map is not a function. Am I reading the data into the code incorrectly? Any help would be appreciated.
edit: I am currently only trying to load the first ap, the json file will be much bigger and I will be creating a pie chart that changes so that it represents each ap.floorratio.
So for now, only the data from the first floorratio array needs to go into the pie chart.
Here's a working version.
var width = 960,
height = 500,
radius = Math.min(width, height) / 2;
var color = d3.scale.ordinal()
.range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]);
var arc = d3.svg.arc()
.outerRadius(radius - 10)
.innerRadius(0);
// defines wedge size
var pie = d3.layout.pie()
.sort(null)
.value(function (d) { return d.ratio; });
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
d3.json("APCategories.json", function(error, data) {
node = data.data[0].ap[0].floorratio; // <------ here
var g = svg.selectAll(".arc")
.data(pie(node))
.enter().append("g")
.attr("class", "arc");
g.append("path")
.attr("d", arc)
.style("fill", function(d) { return color(d.data.floor); });
g.append("text")
.attr("transform", function (d) { return "translate(" + arc.centroid(d) + ")"; })
.attr("dy", ".35em")
.style("text-anchor", "middle")
.text(function (d) { return d.data.floor; });
});
The [0] after floorratio wasn't necessary.
http://bl.ocks.org/steveharoz/0638d230c133da1de385

How can I perform this d3.js magic (Grouped Bar Chart) with JSON rather than CSV?

I am attempting to follow this example: http://bl.ocks.org/3887051
However, instead of a CSV, I have a JSON object.
Now, I saw that I could convert my JSON into a CSV by following the instructions here: How to convert JSON to CSV format and store in a variable
That feels like a hack though.
Here's my JSON:
[{"YEAR":2012,"MONTH":1,"MMM":"JAN","Total_Flights":30,"Completed":21,"Canceled":7,"Aborted":2},
{"YEAR":2012,"MONTH":2,"MMM":"FEB","Total_Flights":54,"Completed":28,"Canceled":20,"Aborted":6},
{"YEAR":2012,"MONTH":3,"MMM":"MAR","Total_Flights":39,"Completed":25,"Canceled":12,"Aborted":2},
{"YEAR":2012,"MONTH":4,"MMM":"APR","Total_Flights":27,"Completed":21,"Canceled":6,"Aborted":0},
{"YEAR":2012,"MONTH":5,"MMM":"MAY","Total_Flights":35,"Completed":21,"Canceled":12,"Aborted":2},
{"YEAR":2012,"MONTH":6,"MMM":"JUN","Total_Flights":15,"Completed":10,"Canceled":4,"Aborted":1},
{"YEAR":2012,"MONTH":7,"MMM":"JUL","Total_Flights":42,"Completed":18,"Canceled":21,"Aborted":3},
{"YEAR":2012,"MONTH":8,"MMM":"AUG","Total_Flights":43,"Completed":29,"Canceled":8,"Aborted":6},
{"YEAR":2012,"MONTH":9,"MMM":"SEP","Total_Flights":28,"Completed":20,"Canceled":8,"Aborted":0},
{"YEAR":2012,"MONTH":10,"MMM":"OCT","Total_Flights":43,"Completed":24,"Canceled":18,"Aborted":1},
{"YEAR":2012,"MONTH":11,"MMM":"NOV","Total_Flights":35,"Completed":18,"Canceled":17,"Aborted":0},
{"YEAR":2012,"MONTH":12,"MMM":"DEC","Total_Flights":45,"Completed":9,"Canceled":32,"Aborted":4},
{"YEAR":2013,"MONTH":1,"MMM":"JAN","Total_Flights":49,"Completed":4,"Canceled":43,"Aborted":2}]
My game plan is to have the chart display four bars for each month: Total, Completed, Canceled and Aborted.
How would I transform this example code to deal with my JSON?
I'll be swimming through the d3.js tutorials here: https://github.com/mbostock/d3/wiki/Tutorials until I figure it out or someone wise shows me the ropes.
I'll periodically update this post with my progress.
UPDATE #1: Anyone coming here should check out these godsend tutorials: http://alignedleft.com/tutorials/d3/
I'm still working on it. Such a powerful library. I'll report back again within a few hours.
After a few days of diving all in D3's documentation and the great tutorials I linked to earlier, I finally created my first graph.
// Make a JSON object out of the data.d string receieved.
json_data = jQuery.parseJSON(data.d)
// width = 960 - 40 - 20 = 900
// height = 500 - 20 - 30 = 450
var margin = { top: 20, right: 20, bottom: 30, left: 40 },
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
// Information on ordinal scales can be found at: https://github.com/mbostock/d3/wiki/Ordinal-Scales
// An ordinal scale that sets the output range from the specified continuous interval (that is, [0, width]).
// The array interval contains two elements representing the min and max numeric values.
// This interval is subdivided into n evenly-spaced bands, where n is the number of (unique) values in the domain.
// The bands may be offset from the edge of the interval and other bands according to the specifided padding,
// which defaults to zero.
// The padding is typically in the range [0,1] (0.1 in this example) and corrseponds to the amount of space
// in the range interval to allocate to padding.
// A value of 0.5 means that the band width will be equal to the padding width.
var x0 = d3.scale.ordinal()
.rangeRoundBands([0, width], .1);
// Constructs a new ordinal scale with an empty domain and an empty range.
// The ordinal scale is invalid (always returning undefined) until an output range is specified).
var x1 = d3.scale.ordinal();
// Information on linear scales can be found at: https://github.com/mbostock/d3/wiki/Quantitative-Scales
// Quantitative scales have a continuous domain, such as the set of real numbers, or dates.
// Linear scales are a type of quantitative scale.
// Linear scales are the most common scale, and a good default choice to map a continuous input domain to a
// continous output range.
// The mapping is linear in that the output range value y can be expressed as a linear function of the
// input domain value x: y = mx + b.
// The input domain is typically a dimension of the data that you want to visualize, such as the height of
// students (measured in meters) in a sample population.
// The output range is typically a dimension of the desired output visualization, such as the height of bars
// (measured in pixels) in a histogram.
// This will set up our y height scale.
var y = d3.scale.linear()
.range([height, 0]);
// Colors of the graph.
//
// First : Total flights #097054 (green)
// Second : Completed flights #6599FF (blue)
// Third : Cancelled flights #FFDE00 (yellow)
// Fourth : Aborted flights #FF9900 (orange)
var color = d3.scale.ordinal()
.range(["#097054", "#6599FF", "#FFDE00", "#FF9900"]);
// Set up the xAxis to use our x0 scale and be oriented on the bottom.
var xAxis = d3.svg.axis()
.scale(x0)
.orient("bottom");
// We don't worry about tickFormat here, as the ticks will be determined by the data.
// Set up the yAxis to use our y scale and be oriented on the left.
// Additionally, set the tick format to display appropriate labels on the axis (taking out for now).
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
// .tickFormat(d3.format(".2s"));
// Set up the svg canvas with the width and height we calculated earlier.
var svg = d3.select("body").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 + ")");
// Move it to the right margin.left pixels, and move it down margin.top pixels
// Our JSON looks like:
// [{ "YEAR": 2012, "MONTH": 1, "MMM": "JAN", "Total": 36, "Completed": 21, "Canceled": 10, "Aborted": 5 },
// { "YEAR": 2012, "MONTH": 2, "MMM": "FEB", "Total": 60, "Completed": 30, "Canceled": 21, "Aborted": 9 }]
// data = d3.nest()
// .key(function (d) { return d.MMM + " " + d.YEAR; })
// .entries(json_data)
data = json_data
// seriesNames = "Total", "Completed", "Canceled" and "Aborted" See, we're filtering out "YEAR", "MONTH" and "MMM"
var seriesNames = d3.keys(data[0]).filter(function (key) { return (key !== "YEAR") && (key !== "MONTH") && (key !== "MMM"); });
// alert(JSON.stringify(seriesNames));
// alert(seriesNames);
data.forEach(function (d) {
d.Flights = seriesNames.map(function (name) { return { name: name, value: +d[name] }; });
//alert("hi --- " + JSON.stringify(d.Flights));
});
//alert(JSON.stringify(data));
//x0.domain(data.map(function (d) { return d.State; }));
// Change State to be MMM, YEAR (for example: "Jan 2012") Could change this to Jan '12
x0.domain(data.map(function (d) { return d.MMM + " " + d.YEAR; }));
//alert(JSON.stringify(data.map(function (d) { return d.MMM + " " + d.YEAR; })));
// //x1.domain(seriesNames).rangeRoundBands([0, x0.rangeBand()]);
x1.domain(seriesNames).rangeRoundBands([0, x0.rangeBand()]);
// //y.domain([0, d3.max(data, function (d) { return d3.max(d.ages, function (d) { return d.value; }); })]);
// // Make the y domain go from 0 up to the max of d.Total (Total flights)
// y.domain([0, d3.max(data, function (d) { return d3.max(d.Total); })]);
y.domain([0, (10 + d3.max(data, function (d) { return d3.max(d.Flights, function (d) { return d.value; }); }))]);
// The axis business
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("# of Flights");
// From this point to...
//var state = svg.selectAll(".state")
// .data(data)
//.enter().append("g")
// .attr("class", "g")
// .attr("transform", function (d) { return "translate(" + x0(d.State) + ",0)"; });
var state = svg.selectAll(".state")
.data(data)
.enter().append("g")
.attr("class", "g")
.attr("transform", function (d) { return "translate(" + x0(d.MMM + " " + d.YEAR) + ",0)"; });
//alert(JSON.stringify(d.Flights[0]));
state.selectAll("rect")
.data(function (d) { return d.Flights; })
.enter().append("rect")
.attr("width", x1.rangeBand())
.attr("x", function (d) { return x1(d.name); })
.attr("y", function (d) { return y(d.value); })
.attr("height", function (d) { return height - y(d.value); })
.style("fill", function (d) { return color(d.name); });
var legend = svg.selectAll(".legend")
.data(seriesNames.slice().reverse())
.enter().append("g")
.attr("class", "legend")
.attr("transform", function (d, i) { return "translate(0," + i * 20 + ")"; });
legend.append("rect")
.attr("x", width - 18)
.attr("width", 18)
.attr("height", 18)
.style("fill", color);
legend.append("text")
.attr("x", width - 24)
.attr("y", 9)
.attr("dy", ".35em")
.style("text-anchor", "end")
.text(function (d) { return d; })
.on("click", function (d) {
alert(d);
//state.selectAll("rect")
//.update()
// .exit().transition()
// .attr("height", 0)
// .remove();
//state.selectAll("rect")
//.update()
//state.selectAll("rect").exit().transition().attr("height", 0).remove();
});
After this graph, it was very easy to make the multiple donut graphs as well as the stacked chart.

d3.js Tag Cloud size from a Json/array?

I am modifying this code: https://github.com/jasondavies/d3-cloud
<script>
d3.layout.cloud().size([300, 300])
.words([
"Hello", "world", "normally", "you", "want", "more", "words",
"than", "this"].map(function(d) {
return {text: d, size: 10 + Math.random() * 90};
}))
.rotate(function() { return ~~(Math.random() * 2) * 90; })
.fontSize(function(d) { return d.size; })
.on("end", draw)
.start();
function draw(words) {
d3.select("body").append("svg")
.attr("width", 300)
.attr("height", 300)
.append("g")
.attr("transform", "translate(150,150)")
.selectAll("text")
.data(words)
.enter().append("text")
.style("font-size", function(d) { return d.size + "px"; })
.attr("text-anchor", "middle")
.attr("transform", function(d) {
return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")";
})
.text(function(d) { return d.text; });
}
</script>
I'd like to get the word and size data from separate JSON data.
I have two variables
jWord = ["abc","def","ghi,"jkl"];
jCount = ["2", "5", "3", "8"];
jWord has the words that I want to display in the tag clouds.
jCount is the size of the corresponding word (same order).
I switched to the word to jWord, but not sure how to switch the size part in
.words(jWord.map(function(d) {
return {text: d, size: 10 + Math.random() * 90};
}))
I also have another Json format variable.
jWord_Count = ["abc":2, "def":5, "ghi":3, "jkl":8 ];
If this format helps.
Try d3.zip: d3.zip(jWord, jCount) returns a merged array where the first element is the text and size of the first word [jWord[0], jCount[0]], the second element is the second word, and so on. For example:
.words(d3.zip(jWord, jCount).map(function(d) {
return {text: d[0], size: d[1]};
}))
In effect, d3.zip turns column-oriented data into row-oriented data. You could also just represent your data in row-oriented form to begin with:
var words = [
{text: "abc", size: 2},
{text: "def", size: 5},
{text: "ghi", size: 3},
{text: "jkl", size: 8}
];
Lastly, watch out with types. Your counts are represented as strings ("2") rather than numbers (2). So you might want to use + to coerce them to numbers.