I am implementing a multi-line series chart using d3.js and I am getting an error pointing to my x-axis when trying to plot my dateTime from the data coming in. "Error: attribute d: Expected number, "MNaN,376.88020650…"."
Here is my function
var data = [{
"Brand": "Toyota",
"Count": 1800,
"Time": "2017-04-02 16"},
{
"Brand": "Toyota",
"Count": 1172,
"Time": "2017-04-02 17"},
{
"Brand": "Toyota",
"Count": 2000,
"Time": "2017-04-02 18"},
{
"Brand": "Honda",
"Count": 8765,
"Time": "2017-04-02 16"},
{
"Brand": "Honda",
"Count": 3445,
"Time": "2017-04-02 17"},
{
"Brand": "Honda",
"Count": 1232,
"Time": "2017-04-02 18"}
]
var dataGroup = d3.nest() //d3 method that groups data by Brand
.key(function(d) {return d.Brand;})
.entries(data);
console.log(JSON.stringify(dataGroup));
//var color = d3.scale.category10();
var vis = d3.select("#visualisation"),
WIDTH = 1000,
HEIGHT = 500,
MARGINS = {
top: 50,
right: 20,
bottom: 50,
left: 50
},
xScale = d3.scaleLinear().range([MARGINS.left, WIDTH - MARGINS.right]).domain([d3.min(data, function(d) { //set up x-axis based on data
return d.Time;
}), d3.max(data, function(d) {
return d.Time;
})]),
yScale = d3.scaleLinear().range([HEIGHT - MARGINS.top, MARGINS.bottom]).domain([d3.min(data, function(d) { //set up y-axis based on data
return d.Count;
}), d3.max(data, function(d) {
return d.Count;
})]),
xAxis = d3.axisBottom()
.scale(xScale),
yAxis = d3.axisLeft()
.scale(yScale)
vis.append("svg:g")
.attr("class", "x axis")
.attr("transform", "translate(0," + (HEIGHT - MARGINS.bottom) + ")")
.call(xAxis);
vis.append("svg:g")
.attr("class", "y axis")
.attr("transform", "translate(" + (MARGINS.left) + ",0)")
.call(yAxis);
var lineGen = d3.line()
.x(function(d) {
return xScale(d.Time);
})
.y(function(d) {
return yScale(d.Count);
})
.curve(d3.curveBasis);
dataGroup.forEach(function(d,i) { //iterate over the dataGroup and create line graph for each brand
vis.append('svg:path')
.attr('d', lineGen(d.values))
.attr('stroke', function(d,j) {
return "hsl(" + Math.random() * 360 + ",100%,50%)"; //random color for each brand line on graph
})
.attr('stroke-width', 2)
.attr('id', 'line_'+d.key)
.attr('fill', 'none');
lSpace = WIDTH/dataGroup.length; //define the legend space based on number of brands
vis.append("text")
.attr("x", (lSpace/2)+i*lSpace)
.attr("y", HEIGHT)
.style("fill", "black")
.attr("class","legend")
.on('click',function(){
var active = d.active ? false : true;
var opacity = active ? 0 : 1;
d3.select("#line_" + d.key).style("opacity", opacity);
d.active = active;
})
.text(d.key);
});
My dates are in yyyy-mm-dd HH format and what I am trying to accomplish is this for example:
"Time": "2017-04-02 16" converted to 'April 02' on the x axis and have the hour (HH) just displayed as a tool tip...etc
Here is a jsfiddle link https://jsfiddle.net/rsov2s2s/
Any help is appreciated.
In your data objects, Time is only a string. Thus, you`ll have to parse it into an actual date:
data.forEach(function(d){
d.Time = d3.timeParse("%Y-%m-%d %H")(d.Time)
});
In this function, d3.timeParse uses "%Y-%m-%d %H" as a specifier, which matches the structure of your strings.
After that, don't forget to change the xScale from scaleLinear to scaleTime.
Here is your code with those changes only:
var data = [{
"Brand": "Toyota",
"Count": 1800,
"Time": "2017-04-02 16"
}, {
"Brand": "Toyota",
"Count": 1172,
"Time": "2017-04-02 17"
}, {
"Brand": "Toyota",
"Count": 2000,
"Time": "2017-04-02 18"
}, {
"Brand": "Honda",
"Count": 8765,
"Time": "2017-04-02 16"
}, {
"Brand": "Honda",
"Count": 3445,
"Time": "2017-04-02 17"
}, {
"Brand": "Honda",
"Count": 1232,
"Time": "2017-04-02 18"
}];
data.forEach(function(d) {
d.Time = d3.timeParse("%Y-%m-%d %H")(d.Time)
});
var dataGroup = d3.nest() //d3 method that groups data by Brand
.key(function(d) {
return d.Brand;
})
.entries(data);
//var color = d3.scale.category10();
var vis = d3.select("#visualisation"),
WIDTH = 1000,
HEIGHT = 500,
MARGINS = {
top: 50,
right: 20,
bottom: 50,
left: 50
},
xScale = d3.scaleTime().range([MARGINS.left, WIDTH - MARGINS.right]).domain([d3.min(data, function(d) { //set up x-axis based on data
return d.Time;
}), d3.max(data, function(d) {
return d.Time;
})]),
yScale = d3.scaleLinear().range([HEIGHT - MARGINS.top, MARGINS.bottom]).domain([d3.min(data, function(d) { //set up y-axis based on data
return d.Count;
}), d3.max(data, function(d) {
return d.Count;
})]),
xAxis = d3.axisBottom()
.scale(xScale),
yAxis = d3.axisLeft()
.scale(yScale)
vis.append("svg:g")
.attr("class", "x axis")
.attr("transform", "translate(0," + (HEIGHT - MARGINS.bottom) + ")")
.call(xAxis);
vis.append("svg:g")
.attr("class", "y axis")
.attr("transform", "translate(" + (MARGINS.left) + ",0)")
.call(yAxis);
var lineGen = d3.line()
.x(function(d) {
return xScale(d.Time);
})
.y(function(d) {
return yScale(d.Count);
})
.curve(d3.curveBasis);
dataGroup.forEach(function(d, i) { //iterate over the dataGroup and create line graph for each brand
vis.append('svg:path')
.attr('d', lineGen(d.values))
.attr('stroke', function(d, j) {
return "hsl(" + Math.random() * 360 + ",100%,50%)"; //random color for each brand line on graph
})
.attr('stroke-width', 2)
.attr('id', 'line_' + d.key)
.attr('fill', 'none');
lSpace = WIDTH / dataGroup.length; //define the legend space based on number of brands
vis.append("text")
.attr("x", (lSpace / 2) + i * lSpace)
.attr("y", HEIGHT)
.style("fill", "black")
.attr("class", "legend")
.on('click', function() {
var active = d.active ? false : true;
var opacity = active ? 0 : 1;
d3.select("#line_" + d.key).style("opacity", opacity);
d.active = active;
})
.text(d.key);
});
.axis path {
fill: none;
stroke: #777;
shape-rendering: crispEdges;
}
.axis text {
font-family: Lato;
font-size: 13px;
}
.legend {
font-size: 14px;
font-weight: bold;
cursor: pointer;
<title>D3 Test</title>
<script src="https://d3js.org/d3.v4.js"></script>
<body>
<svg id="visualisation" width="1000" height="600"></svg>
<script src="InitChart.js"></script>
</body>
Related
I'm trying to show a vertical bar chart with x and y axes. I get the bar chart with y axis, however I'm struggling with the x-axis.
The x-axis text labels are equally distributed with the width of the bars, however: there are markers/vertical lines on the x-axis with varying width, particularly the first and last sections, even though I've specified the scaleBand and the domain.
My code:
<script src="https://d3js.org/d3.v5.min.js"></script>
<svg class="v5chart" width="960" height="500"></svg>
<style>
/*Rectangle bar class styling*/
.bar {
fill: #0080FF
}
.bar:hover {
fill: #003366
}
/*Text class styling*/
.text {
fill: white;
font-family: sans-serif
}
</style>
<script>
////VERTICAL BAR CHART WITH SVG AND NAMES
// Create data array of values to visualize
var dataArray = [{ "Player": "John Doe", "Points": 23 }, { "Player": "Jane Doe", "Points": 13 }, { "Player": "Mary Jane", "Points": 21 }, { "Player": "Debasis Das", "Points": 14 }, { "Player": "Nishant", "Points": 37 }, { "Player": "Mark", "Points": 15 }, { "Player": "Andrew", "Points": 18 }, { "Player": "Simon", "Points": 34 }, { "Player": "Lisa", "Points": 30 }, { "Player": "Marga", "Points": 20 }];
// Create variable for the SVG
var canvas = d3.select(".v5chart1").append("g").attr("transform", "translate(20,30)");
var canvasWidth = 500;
var maxValue = d3.max(dataArray, function (d) { return d.Points; });
var canvasHeight = maxValue*10;
var heightScale = d3.scaleLinear()
.domain([0, d3.max(dataArray, function (d) { return d.Points; })])
.range([canvasHeight, 0]); //use max value (37) * 10
var y_axis = d3.axisLeft()
.scale(heightScale);
var x = d3.scaleBand()
.rangeRound([0, canvasWidth], .1);
x.domain(dataArray.map(function (d) { return d.Player; }));
var x_Axis = d3.axisBottom(x);
// Select, append to SVG, and add attributes to rectangles for bar chart
canvas.selectAll("rect")
.data(dataArray)
.enter().append("rect")
.attr("class", "bar")
.attr("height", function (d, i) { return (d.Points * 10) })
.attr("width", canvasWidth/dataArray.length)
.attr("x", function (d, i) { return (i * (canvasWidth / dataArray.length)) })
.attr("y", function (d, i) { return canvasHeight - (d.Points * 10) });
// Select, append to SVG, and add attributes to text
canvas.selectAll("text")
.data(dataArray)
.enter().append("text")
.text(function (d) { return d.Points })
.attr("class", "text")
.attr("x", function (d, i) { return (i * (canvasWidth / dataArray.length)) + (canvasWidth / dataArray.length)/2 })
.attr("y", function (d, i) { return canvasHeight + 20 - (d.Points * 10) });
canvas.append("g")
.attr("transform", "translate(0,0)")
.call(y_axis);
canvas.append("g")
.attr("transform", "translate(0," + canvasHeight + ")")
.call(x_Axis)
.selectAll("text")
.attr("x",40)
.attr("transform", function (d) {
return "rotate(65)"
});
</script>
I already checked here: https://www.d3-graph-gallery.com/graph/custom_axis.html
You should have read properly the scaleBand example on the link that you provided:
scaleBand provides a convenient bandwidth() method to provide you with the width for each bar
the idea od axis in d3js is that you don't need to do calculations yourself, so in your case you can just pass the player name to the x function and it will do the coordinate calculations for you.
same applies to the y calculations, but I leave this for you to figure out, it should not be hard at all.
one more small thing about scaleBand, you were using rangeRound() method, which I am not familiar with, but if you use range() method combined with padding() as it is in the example you linked, then by adjusting the padding value you can control the width of the bar, without affecting the x axis. The higher value, the thinner will be the bar and more space would be between the bars.
////VERTICAL BAR CHART WITH SVG AND NAMES
// Create data array of values to visualize
var dataArray = [{ "Player": "John Doe", "Points": 23 }, { "Player": "Jane Doe", "Points": 13 }, { "Player": "Mary Jane", "Points": 21 }, { "Player": "Debasis Das", "Points": 14 }, { "Player": "Nishant", "Points": 37 }, { "Player": "Mark", "Points": 15 }, { "Player": "Andrew", "Points": 18 }, { "Player": "Simon", "Points": 34 }, { "Player": "Lisa", "Points": 30 }, { "Player": "Marga", "Points": 20 }];
// Create variable for the SVG
var canvas = d3.select(".v5chart").append("g").attr("transform", "translate(20,30)");
var canvasWidth = 500;
var maxValue = d3.max(dataArray, function (d) { return d.Points; });
var heightScale = d3.scaleLinear()
.domain([0, d3.max(dataArray, function (d) { return d.Points; })])
.range([maxValue * 10, 0]); //use max value (37) * 10
var y_axis = d3.axisLeft()
.scale(heightScale);
var x = d3.scaleBand()
.range([0, canvasWidth]).padding([0.1]);
x.domain(dataArray.map(function (d) { return d.Player; }));
var x_Axis = d3.axisBottom(x);
// Select, append to SVG, and add attributes to rectangles for bar chart
canvas.selectAll("rect")
.data(dataArray)
.enter().append("rect")
.attr("class", "bar")
.attr("height", function (d, i) { return (d.Points * 10) })
.attr("width", x.bandwidth())
.attr("x", function (d, i) { return x(d.Player); })
.attr("y", function (d, i) { return 370 - (d.Points * 10) });
// Select, append to SVG, and add attributes to text
canvas.selectAll("text")
.data(dataArray)
.enter().append("text")
.text(function (d) { return d.Points })
.attr("class", "text")
.attr("text-anchor", "middle")
.attr("x", function (d, i) { return x(d.Player)+x.bandwidth()/2; })
.attr("y", function (d, i) { return 390 - (d.Points * 10) });
canvas.append("g")
.attr("transform", "translate(0,0)")
.call(y_axis);
canvas.append("g")
.attr("transform", "translate(0,370)")
.call(x_Axis);
.bar {
fill: #0080FF
}
.bar:hover {
fill: #003366
}
/*Text class styling*/
.text {
fill: white;
font-family: sans-serif
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg class="v5chart" width="960" height="500"></svg>
I am trying to get values from a JSON File and use them as the X and Y axis on a d3 v4 bar chart. But my axis is not showing up as I like. WHat am I doing wrong?
My HTML Code:
<div class="col" id="main-chart" style="padding-top:75px;">
<svg width="675" height="415"></svg>
</div>
My D3 Code:
var svg = d3.select("#main-chart svg"),
margin = {top: 20, right: 20, bottom: 30, left: 75},
width = +svg.attr("width") - margin.left - margin.right,
height = +svg.attr("height") - margin.top - margin.bottom;
var tooltip = d3.select("body").append("div").attr("class", "toolTip");
var x = d3.scaleBand().rangeRound([0, width]).padding(0.1),
y = d3.scaleLinear().rangeRound([height, 0]);
var colours = d3.scaleOrdinal().range(["#6F257F", "#CA0D59"]);
var g = svg.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
d3.json(data.json, function(error, data) {
if (error) throw error;
x.domain(data.map(function(d) { return d.date; }));
y.domain([0, d3.max(data, function(d) { return d.values; })]);
g.append("g")
.attr("class", "axis axis--x")
.attr("transform", "translate(0," + height + ")")
// .attr("transform", "rotate(-90deg)")
.call(d3.axisBottom(x).ticks(5));
g.append("g")
.attr("class", "axis axis--y")
.call(d3.axisLeft(y).ticks(5).tickFormat(function(d) {return parseInt(d); }).tickSizeInner([-width]))
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", "0.71em")
.attr("text-anchor", "end")
.attr("fill", "#5D6971");
g.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("x", function(d) {return x(d.date); })
.attr("y", function(d) {return y(d.values); })
.attr("width", x.bandwidth())
.attr("height", function(d) { return height - y(d.values); })
.attr("fill", function(d) { return colours(d.date); })
.on("mousemove", function(d){
tooltip
.style("left", d3.event.pageX - 50 + "px")
.style("top", d3.event.pageY - 70 + "px")
.style("display", "inline-block")
.html((d.date) + "<br>" + (d.values));
})
.on("mouseout", function(d){ tooltip.style("display", "none");});
});
My JSON CODE:
[
{
"date": "2018-10-19",
"values": 6574406
},
{
"date": "2018-10-20",
"values": 6575406
},
{
"date": "2018-10-21",
"values": 6575696
},
{
"date": "2018-10-22",
"values": 6576656
},
{
"date": "2018-10-23",
"values": 6577222
},
{
"date": "2018-10-24",
"values": 6578908
},
{
"date": "2018-10-25",
"values": 6579386
},
{
"date": "2018-10-26",
"values": 6580020
},
{
"date": "2018-10-27",
"values": 6580214
},
{
"date": "2018-10-28",
"values": 6580440
},
{
"date": "2018-10-29",
"values": 6581334
},
{
"date": "2018-10-30",
"values": 6583556
},
{
"date": "2018-10-31",
"values": 6584098
},
{
"date": "2018-11-01",
"values": 6584660
}
]
My chart looks smushed and I want my Y-Axis to start with the lowest value. Which in this case is 6574406 and want to increment by 25 with 10 ticks. I have tried many variations but am not able to get the x-axis un-overlapped. I tried to skew the values but that did not work either.
My chart:
I am using D3 charting library to create charts with Angular-cli. D3 version is 4.2.2. Following is what I am trying to create multi-line chart.
import {Directive, ElementRef} from '#angular/core';
import * as D3 from 'd3';
#Directive({
selector: 'bar-graph'
})
export class BarGraphDirective {
private htmlElement:HTMLElement;
constructor(elementRef:ElementRef) {
this.htmlElement = elementRef.nativeElement; // reference to <bar-graph> element from the main template
console.log(this.htmlElement);
console.log(D3);
let d3:any = D3;
var data = [{
"date": "2016-10-01",
"sales": 110,
"searches": 67
}, {
"date": "2016-10-02",
"sales": 120,
"searches": 67
}, {
"date": "2016-10-03",
"sales": 125,
"searches": 69.4
}, {
"date": "2016-10-04",
"sales": 100,
"searches": 67
},{
"date": "2016-10-05",
"sales": 99,
"searches": 66
},{
"date": "2016-10-06",
"sales": 131,
"searches": 67
},{
"date": "2016-10-07",
"sales": 111,
"searches": 47
},{
"date": "2016-10-08",
"sales": 110,
"searches": 67
},{
"date": "2016-10-09",
"sales": 130,
"searches": 67
},{
"date": "2016-10-10",
"sales": 110,
"searches": 67
},{
"date": "2016-10-11",
"sales": 110,
"searches": 67
}];
// set the dimensions and margins of the graph
var margin = {
top: 20,
right: 80,
bottom: 30,
left: 50
},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
// parse the date / time
var parseDate = d3.timeParse("%Y-%m-%d");
// set the ranges
var x = d3.scaleTime().range([0, width]);
var y = d3.scaleLinear().range([height, 0]);
// define the line
var line = d3.line()
.x(function (d) {
return x(d.date);
})
.y(function (d) {
return y(d.sales);
});
var svg = d3.select(this.htmlElement).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 + ")");
// format the data
data.forEach(function (d) {
d.date = parseDate(d.date);
});
x.domain(d3.extent(data, function (d) {
return d.date;
}));
y.domain([0, d3.max(data, function (d) {
return d.sales > d.searches ? d.sales : d.searches;
})]);
// Add the line path.
svg.append("path")
.attr("class", "line")
.style("fill", "none")
.attr("d", line(data))
.style("stroke", "orange");
// change line to look at searches
line.y(function (d) {
return y(d.searches);
});
// Add the second line path.
svg.append("path")
.attr("class", "line")
.style("fill", "none")
.attr("d", line(data))
.style("stroke", "steelblue");
// Add the scatterplot
svg.selectAll("dot")
.data(data)
.enter().append("circle")
.attr("r", 5)
.attr("cx", function(d) { return x(d.date); })
.attr("cy", function(d) { return y(d.sales); });
// Add the X Axis
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));
// Add the Y Axis
svg.append("g")
.call(d3.axisLeft(y))
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Price ($)");
}
}
Then my chart looks as below.
How to add scatterplots to both lines and how to change color of scatterplots as same as of the line ?
Any suggestions are highly appreciated.
Thank You
// Add sales to the scatterplot
svg.selectAll(".sales-circle")
.data(data)
.enter().append("circle")
.attr('class', 'sales-circle')
.attr("r", 5)
.attr("cx", function(d) { return x(d.date); })
.attr("cy", function(d) { return y(d.sales); })
.style("fill", "orange");
// Add searches to the scatterplot
svg.selectAll(".searches-circle")
.data(data)
.enter().append("circle")
.attr("r", 5)
.attr('class', 'searches-circle')
.attr("cx", function(d) { return x(d.date); })
.attr("cy", function(d) { return y(d. searches); })
.style("fill", "steelblue");
I am trying to compose a D3 pie component in each node of a tree.
I am able to build separately the tree and one pie, but I couldn't figure out how to compose them.
Basically, I have the following json data:
window.json = {
"health": [{
"value": 60
}, {
"value": 10
}, {
"value": 30
}],
"color": orange,
"children": [{
"health": [{
"value": 60
}, {
"value": 20
}, {
"value": 20
}],
"color": green
}, {
"health": [{
"value": 40
}, {
"value": 30
}, {
"value": 30
}],
"color": orange
}]
};
It represents the tree. Each node contains data for a pie: it's the "health" properties.
I've build the tree here: http://jsfiddle.net/4srt30pj/4/
I can build a single pie: http://jsfiddle.net/4srt30pj/5/
But I can't see how to mix them together, so that each node shows a pie. I've tried to create a function that draws a pie component:
function drawPie(selection, node) {
selection.data(node, function(d, i) {
console.log(node);
console.log(d);
console.log(i);
return pie(d.health);
})
.enter()
.append('path')
.attr('d', arc)
.attr('fill', function (d, i) {
return color(i);
});
}
Then call it for each tree nodes:
drawPie(vis.selectAll("g.node"), nodes);
(the code is there: http://jsfiddle.net/4srt30pj/6/ )
But it doesn't show the pies.
Is it possible to achieve this composition?
You are close. Try:
function drawPie(d) {
d3.select(this)
.selectAll('path')
.data(pie(d.health))
.enter()
.append('path')
.attr('d', arc)
.attr('fill', function(d, i) {
return color(i);
});
}
nodeEnter.each(drawPie);
Full working sample:
<!DOCTYPE html>
<html>
<head>
<script data-require="d3#3.5.3" data-semver="3.5.3" src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.3/d3.js"></script>
<style>
path.link {
fill: none;
stroke-width: 5px;
}
svg text {
font-family: Roboto, Arial;
}
.selected {
display: none;
}
</style>
</head>
<body>
<script>
var red = "#f5696d";
var green = "#40bc96";
var orange = "#fabd57";
window.json = {
"health": [{
"value": 60
}, {
"value": 10
}, {
"value": 30
}],
"color": orange,
"children": [{
"health": [{
"value": 60
}, {
"value": 20
}, {
"value": 20
}],
"color": green
}, {
"health": [{
"value": 40
}, {
"value": 30
}, {
"value": 30
}],
"color": orange
}]
};
var w = 100;
var h = 60;
var i = 0;
var root;
var tree = d3.layout.tree()
.nodeSize([w + 10, h + 20])
.separation(function(a, b) {
return (a.parent == b.parent ? 1 : 1.5);
});
var diagonal = d3.svg.diagonal()
.projection(function(d) {
return [d.x, d.y];
});
var vis = d3.select("body").append("svg:svg")
.attr("width", 500)
.attr("height", 500)
.append("svg:g")
.attr("transform", "translate(" + 250 + "," + 30 + ")");
root = window.json;
root.x0 = 0;
root.y0 = 0;
function toggleAll(d) {
if (d.children) {
d.children.forEach(toggleAll);
toggle(d);
}
}
var arc = d3.svg.arc()
.outerRadius(30)
.innerRadius(0);
var pie = d3.layout.pie()
.value(function(d) {
return d.value;
})
.sort(null);
var color = d3.scale.ordinal()
.range(['#40bc96', '#fabd57', '#f5696d']);
function drawPie(d) {
d3.select(this)
.selectAll('path')
.data(pie(d.health))
.enter()
.append('path')
.attr('d', arc)
.attr('fill', function(d, i) {
return color(i);
});
}
update(root);
function update(source) {
var duration = d3.event && d3.event.altKey ? 5000 : 500;
// Compute the new tree layout.
var nodes = tree.nodes(root).reverse();
// Update the nodes…
var node = vis.selectAll("g.node")
.data(nodes, function(d) {
return d.id || (d.id = ++i);
});
// Enter any new nodes at the parent's previous position.
var nodeEnter = node.enter().append("svg:g")
.attr("class", "node")
.attr("transform", function(d) {
return "translate(" + source.x0 + "," + source.y0 + ")";
});
nodeEnter
.each(drawPie);
// Transition nodes to their new position.
var nodeUpdate = node.transition()
.duration(duration)
.attr("transform", function(d) {
return "translate(" + d.x + "," + d.y + ")";
});
// Update the links…
var link = vis.selectAll("path.link")
.data(tree.links(nodes), function(d) {
return d.target.id;
});
// Enter any new links at the parent's previous position.
link.enter().insert("svg:path", "g")
.attr("class", "link")
.style("stroke-opacity", 0.4)
.style("stroke", function(d) {
return d.target.color;
})
.attr("d", function(d) {
var o = {
x: source.x0,
y: source.y0
};
return diagonal({
source: o,
target: o
});
})
.transition()
.duration(duration)
.attr("d", diagonal);
// Stash the old positions for transition.
nodes.forEach(function(d) {
d.x0 = d.x;
d.y0 = d.y;
});
}
</script>
</body>
</html>
Here is a link to the jsfiddle
http://jsfiddle.net/jaimem/RPGPL/2/
Now the graph shows red color for all the circles.Is dere a way to show random colors on the circles.
Here is the d3.js code
var data = [{ "count": "202", "year": "1590"},
{ "count": "215", "year": "1592"},
{ "count": "179", "year": "1593"},
{ "count": "199", "year": "1594"},
{ "count": "134", "year": "1595"},
{ "count": "176", "year": "1596"},
{ "count": "172", "year": "1597"},
{ "count": "161", "year": "1598"},
{ "count": "199", "year": "1599"},
{ "count": "181", "year": "1600"},
{ "count": "157", "year": "1602"},
{ "count": "179", "year": "1603"},
{ "count": "150", "year": "1606"},
{ "count": "187", "year": "1607"},
{ "count": "133", "year": "1608"},
{ "count": "190", "year": "1609"},
{ "count": "175", "year": "1610"},
{ "count": "91", "year": "1611"},
{ "count": "150", "year": "1612"} ];
function ShowGraph(data) {
d3.selectAll('.axis').remove();
var vis = d3.select("#visualisation").append('svg'),
WIDTH = 500,
HEIGHT = 500,
MARGINS = {
top: 20,
right: 20,
bottom: 20,
left: 30
},
xRange = d3.scale
.linear()
.domain([
d3.min(data, function(d){ return parseInt(d.year, 10);}),
d3.max(data, function(d){ return parseInt(d.year, 10);})
])
.range([MARGINS.left, WIDTH - MARGINS.right]),
yRange = d3.scale
.linear()
.domain([
d3.min(data, function(d){ return parseInt(d.count, 10);}),
d3.max(data, function(d){ return parseInt(d.count, 10);})
])
.range([HEIGHT - MARGINS.top, MARGINS.bottom]),
xAxis = d3.svg.axis() // generate an axis
.scale(xRange) // set the range of the axis
.tickSize(5) // height of the ticks
.tickSubdivide(true), // display ticks between text labels
yAxis = d3.svg.axis() // generate an axis
.scale(yRange) // set the range of the axis
.tickSize(5) // width of the ticks
.orient("left") // have the text labels on the left hand side
.tickSubdivide(true); // display ticks between text labels
var transition = vis.transition().duration(1000).ease("exp-in-out");
transition.select(".x.axis").call(xAxis);
transition.select(".y.axis").call(yAxis);
vis.append("svg:g") // add a container for the axis
.attr("class", "x axis") // add some classes so we can style it
.attr("transform", "translate(0," + (HEIGHT - MARGINS.bottom) + ")") // move it into position
.call(xAxis); // finally, add the axis to the visualisation
vis.append("svg:g")
.attr("class", "y axis")
.attr("transform", "translate(" + (MARGINS.left) + ",0)")
.call(yAxis);
var circles = vis.selectAll("circle").data(data)
circles.enter()
.append("svg:circle")
.attr("cx", function (d) {
return xRange(d.year);
})
.attr("cy", function (d) {
return yRange(d.count);
})
.style("fill", "red")
circles.transition().duration(1000)
.attr("cx", function (d) {
return xRange(d.year);
})
.attr("cy", function (d) {
return yRange(d.count);
})
.attr("r", 10)
circles.exit()
.transition().duration(1000)
.attr("r", 10)
.remove();
}
you can also use d3.scale.category20(); to get some predefined random colors
Just define color scale as
var color = d3.scale.category20();
Add add fill attribute to the circles as
.attr("fill",function(d,i){return color(i);});
replace .style("fill","red") with
.style("fill",function() {
return "hsl(" + Math.random() * 360 + ",100%,50%)";
})
doc for dynamic properties
For a quick-and-dirty approach to random colors:
const dataset = [12, 31, 22, 17, 25, 18, 29, 14, 9];
d3.select("body").selectAll("div")
.data(dataset)
.enter()
.append("div")
.attr("class", "bar")
.style('height',(data) => { return data+'px' })
.style('background-color',() => {
let color = '#'+Math.floor(Math.random() * Math.pow(2,32) ^ 0xffffff).toString(16).substr(-6);
console.log(color);
return color;
})
.bar {
width: 25px;
height: 100px;
display: inline-block;
}
<script src="//cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.js"></script>
May be the Chumliu answer is the first approach, but it has one fault: it will repeat colors and make a confusion for the when read the graphics.
Like this way you have different colors:
var colors = [];
var arr = [];
var j;
products.forEach(function(d)
{
do
{
j = Math.random();
}
while($.inArray(j,arr) != -1);
arr.push(j);
//this gives us different values
var value = parseFloat(d.category_id) + parseFloat(d.total);
eval('colors.cat'+d.category_id+' = "hsl('+ parseFloat('0.'+ value ) * 360 + ',100%,50%)"');
}
later you can use it in D3 like this:
g.append("path").style("fill", function(d)
{
var indexcolor = 'cat'+d.data.category_id; return colors[indexcolor];
});