Related
I am displaying the following boxplot and would like to give it style features like: resize it to 400x800px , display it in the middle of the html file... Now I cant see the x axis labels for example because of the size... Any help?
Please check the complete code on this plunker.
The script is starting like this:
var labels = true; // show the text labels beside individual boxplots?
var margin = {top: 25, right: 25, bottom: 25, left: 25};
var width = 800 - margin.left - margin.right;
var height = 400 - margin.top - margin.bottom;
var min = 0,
max = 10;
// parse in the data
d3.csv("boxplot_year.csv", function(error, csv) {
var data = [];
data[0] = [];
data[1] = [];
data[2] = [];
data[3] = [];
data[4] = [];
data[5] = [];
data[0][0] = "Y2010";
data[1][0] = "Y2011";
data[2][0] = "Y2012";
data[3][0] = "Y2013";
data[4][0] = "Y2014";
data[5][0] = "Y2015";
data[0][1] = [];
data[1][1] = [];
data[2][1] = [];
data[3][1] = [];
data[4][1] = [];
data[5][1] = [];
csv.forEach(function(x) {
var v1 = Math.floor(x.Y2010),
v2 = Math.floor(x.Y2011),
v3 = Math.floor(x.Y2012),
v4 = Math.floor(x.Y2013),
v5 = Math.floor(x.Y2014),
v6 = Math.floor(x.Y2015);
var rowMax = Math.max(Math.max(v1,v2), Math.max(Math.max(v3,v4), Math.max(v5,v6)));
var rowMin = Math.min(Math.min(v1,v2), Math.min(Math.min(v3,v4), Math.min(v5,v6)));
data[0][1].push(v1);
data[1][1].push(v2);
data[2][1].push(v3);
data[3][1].push(v4);
data[4][1].push(v5);
data[5][1].push(v6);
if (rowMax > max) max = rowMax;
if (rowMin < min) min = rowMin;
});
var boxplot = d3.box()
.whiskers(iqr(1.5))
.height(height)
.domain([min, max])
.showLabels(labels);
var svg = d3.select("#boxplot").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.attr("class", "box")
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// the x-axis
var x = d3.scale.ordinal()
.domain( data.map(function(d) { console.log(d); return d[0]; } ) )
.rangeRoundBands([0 , width], 0.7, 0.3);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
// the y-axis
var y = d3.scale.linear()
.domain([min, max])
.range([height + margin.top, 0 + margin.top]);
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
// draw the boxplots
svg.selectAll(".box")
.data(data)
.enter().append("g")
.attr("transform", function(d) { return "translate(" + x(d[0]) + "," + margin.top + ")"; } )
.call(boxplot.width(x.rangeBand()));
// draw y axis
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text") // and text1
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "middle")
.style("font-size", "10px")
.text("Grade");
// draw x axis
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + (height + margin.top + 10) + ")")
.call(xAxis)
.append("text") // text label for the x axis
.attr("x", (width / 2) )
.attr("y", 10 )
.attr("dy", ".71em")
.style("text-anchor", "middle")
.style("font-size", "10px")
.text("Year");
});
// Returns a function to compute the interquartile range.
function iqr(k) {
return function(d, i) {
var q1 = d.quartiles[0],
q3 = d.quartiles[2],
iqr = (q3 - q1) * k,
i = -1,
j = d.length;
while (d[++i] < q1 - iqr);
while (d[--j] > q3 + iqr);
return [i, j];
};
}
You can adjust the bottom margin to 100. This is sufficient to show the bottom y-axis.
var margin = {top: 25, right: 25, bottom: 100, left: 25};
Based on your comment, to make both axis unite at 0 add a transform to your y-axis
svg.append("g")
.attr("class", "y axis")
.attr("transform", "translate (0,10)")
.call(yAxis)
To get rid of the Y from Y2010 add a slice to your labels like below. However be aware that it is changing your data so in your console log you will see years as 2010, 2011 etc.
// the x-axis
var x = d3.scale.ordinal()
.domain( data.map(function(d) { d[0] = d[0].slice(1); console.log(d); return d[0]; } ) )
.rangeRoundBands([0 , width], 0.7, 0.3);
Hope this helps.
Remove the width and height attributes on your svg and make it expand to full size of its outer container using the viewBox attribute, replace the var svg part as follows, I hard coded the viewBox, change it as you see fit:
var svg = d3.select("#boxplot").append("svg")
.attr("viewBox","0 0 800 800")
.attr("preserveAspectRatio","none")
.style("display","block")
.style("width","100%")
.style("height","100%")
.attr("class", "box")
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
Since you now make your svg expand as much as possible, only modify the outer div as you see fit, either on "resize", periodically etc. To better understand what viewBox does: https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/viewBox
I'm trying to figure out how to get two d3 graphs onto the same page with one on the left and one on the right. However, what I'm getting is this.
This is my html file.
<!DOCTYPE html>
<meta charset="utf-8">
<style>
svg {
font: 10px sans-serif;
}
.polyline path {
fill: none;
stroke: #666;
shape-rendering: crispEdges;
}
.axis line,
.axis path {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.axis text {
text-shadow: 0 1px 0 #fff, 1px 0 0 #fff, 0 -1px 0 #fff, -1px 0 0 #fff;
cursor: move;
}
.xaxis text {
font: 10px sans-serif;
}
.yaxis text {
font: 10px sans-serif;
}
.xaxis path,
.xaxis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.yaxis path,
.yaxis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
</style>
<body>
<svg class="chart"></svg>
<script src="//d3js.org/d3.v3.min.js"></script>
<script src = "project3.js">//https://my.up.ist.psu.edu/lng5099/project3.html </script>
</body>
</html>
This is my js file.
(function() {
var margin = {top: 20, right: 30, bottom: 30, left: 40},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var x = d3.scale.ordinal().rangePoints([0, width], 1),
y = {};
var axis = d3.svg.axis().orient("left");
var line = d3.svg.line() //define a function to convert points into a polyline
.x(function(d) { return d.x; })
.y(function(d) { return d.y; })
.interpolate("linear");//line style. you can try "cardinal".
var chart = d3.select(".chart")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var cars=[];
d3.csv("cars.csv", type, function(error, data) {
cars = data;
drawPC();
});
function drawPC() {
// Extract the list of dimensions and create a scale for each.
for (var dim in cars[0]) {
if (dim != "name") {
y[dim] = d3.scale.linear()
.domain([d3.min(cars, function(d) { return +d[dim]; }), d3.max(cars, function(d) { return +d[dim]; })])
.range([height,0]);
}
}
x.domain(dimensions = d3.keys(cars[0]).filter(function(d) { return d != "name";}));
//draw polylines
for (var i=1; i< cars.length; i++) { //for each car
//prepare the coordinates for a polyline
var lineData = []; //initialize an array for coordinates of a polyline
for (var prop in cars[0]) { //get each dimension
if (prop != "name" ) { //skip the name dimension
var point = {}; //initialize a coordinate object
var val = cars[i][prop]; //obtain the value of a car in a dimension
point['x'] = x(prop); //x value: mapping the dimension
point['y'] = y[prop](val);//y value: mapping the value in that dimension
lineData.push(point); //add the object into the array
}
}
//draw a polyline based on the coordindates
chart.append("g")
.attr("class", "polyline")
.append("path") // a path shape
.attr("d", line(lineData)); //line() is a function to turn coordinates into SVG commands
}
//next: draw individual dimension lines
//position dimension lines appropriately
var g = chart.selectAll(".dimension")
.data(dimensions)
.enter().append("g")
.attr("class", "dimension")
.attr("transform", function(d) { return "translate(" + x(d) + ")"; }); //translate each axis
// Add an axis and title.
g.append("g")
.attr("class", "axis")
.each(function(d) { d3.select(this).call(axis.scale(y[d])); })
.append("text")
.style("text-anchor", "middle")
.attr("y", -9)
.text(function(d) { return d; });
};
//this function coerces numerical data to numbers
function type(d) {
d.economy = +d.economy; // coerce to number
d.displacement = +d.displacement; // coerce to number
d.power = +d.power; // coerce to number
d.weight = +d.weight; // coerce to number
d.year = +d.year;
return d;
}
})();
(function() {
var margin = {top: 20, right: 30, bottom: 30, left: 40},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var x = d3.scale.linear().range([50, width]),
y = d3.scale.linear().range([height-20,0]);
var chart = d3.select(".chart")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var xAxis = d3.svg.axis().scale(x).orient("bottom");
var yAxis = d3.svg.axis().scale(y).orient("left");
var cars=[];
d3.csv("cars.csv", type, function(error, data) {
cars = data;
drawXY();
});
function drawXY(){
x.domain([d3.min(cars, function(d) { return d.year; }), d3.max(cars, function(d) { return d.year; })]);
y.domain([d3.min(cars, function(d) { return d.power; }), d3.max(cars, function(d) { return d.power; })]);
var yPos = height -20;
chart.append("g")
.attr("class", "xaxis")
.attr("transform", "translate(0," + yPos + ")")
.call(xAxis);
chart.append("g")
.attr("class", "yaxis")
.attr("transform", "translate(50,0)")
.call(yAxis);
chart.selectAll(".dot")
.data(cars)
.enter().append("circle")
.attr("class", "dot")
.attr("cx", function(d) { return x(d.year); })
.attr("cy", function(d) { return y(d.power); })
.attr("r", 3);
}
d3.selectAll("circle").data(cars).enter()
.append("circle")
.classed("circle", true)
.on("mouseover", function() { d3.select(d3.event.target).classed("highlight", true); })
.on("mouseout", function() { d3.select(d3.event.target).classed("highlight", false); });
function type(d) {
d.economy = +d.economy; // coerce to number
d.displacement = +d.displacement; // coerce to number
d.power = +d.power; // coerce to number
d.weight = +d.weight; // coerce to number
d.year = +d.year;
return d;
}
})();
Both are displaying, but I'm not sure how set it so that they position properly. Please help.
Figured it out there was an issue with the positioning of my margins, width and height. There is the java code for anyone who needs the help.
(function() {
var margin = {top: 20, right: 30, bottom: 30, left: 40},
width = 700 - margin.left - margin.right,
height = 600 - margin.top - margin.bottom;
var x = d3.scale.ordinal().rangePoints([0, width], 1),
y = {};
var axis = d3.svg.axis().orient("left");
var line = d3.svg.line() //define a function to convert points into a polyline
.x(function(d) { return d.x; })
.y(function(d) { return d.y; })
.interpolate("linear");//line style. you can try "cardinal".
var chart = d3.select(".chart")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var cars=[];
d3.csv("cars.csv", type, function(error, data) {
cars = data;
drawPC();
});
function drawPC() {
// Extract the list of dimensions and create a scale for each.
for (var dim in cars[0]) {
if (dim != "name") {
y[dim] = d3.scale.linear()
.domain([d3.min(cars, function(d) { return +d[dim]; }), d3.max(cars, function(d) { return +d[dim]; })])
.range([height,0]);
}
}
x.domain(dimensions = d3.keys(cars[0]).filter(function(d) { return d != "name";}));
//draw polylines
for (var i=1; i< cars.length; i++) { //for each car
//prepare the coordinates for a polyline
var lineData = []; //initialize an array for coordinates of a polyline
for (var prop in cars[0]) { //get each dimension
if (prop != "name" ) { //skip the name dimension
var point = {}; //initialize a coordinate object
var val = cars[i][prop]; //obtain the value of a car in a dimension
point['x'] = x(prop); //x value: mapping the dimension
point['y'] = y[prop](val);//y value: mapping the value in that dimension
lineData.push(point); //add the object into the array
}
}
//draw a polyline based on the coordindates
chart.append("g")
.attr("class", "polyline")
.append("path") // a path shape
.attr("d", line(lineData)); //line() is a function to turn coordinates into SVG commands
}
//next: draw individual dimension lines
//position dimension lines appropriately
var g = chart.selectAll(".dimension")
.data(dimensions)
.enter().append("g")
.attr("class", "dimension")
.attr("transform", function(d) { return "translate(" + x(d) + ")"; }); //translate each axis
// Add an axis and title.
g.append("g")
.attr("class", "axis")
.each(function(d) { d3.select(this).call(axis.scale(y[d])); })
.append("text")
.style("text-anchor", "middle")
.attr("y", -9)
.text(function(d) { return d; });
};
//this function coerces numerical data to numbers
function type(d) {
d.economy = +d.economy; // coerce to number
d.displacement = +d.displacement; // coerce to number
d.power = +d.power; // coerce to number
d.weight = +d.weight; // coerce to number
d.year = +d.year;
return d;
}
})();
(function() {
var margin = {top: 20, right: 30, bottom: 30, left: 690},
width = 1300 - margin.left - margin.right,
height = 600 - margin.top - margin.bottom;
var x = d3.scale.linear().range([50, width]),
y = d3.scale.linear().range([height-20,0]);
var chart = d3.select(".chart")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var xAxis = d3.svg.axis().scale(x).orient("bottom");
var yAxis = d3.svg.axis().scale(y).orient("left");
var cars=[];
d3.csv("cars.csv", type, function(error, data) {
cars = data;
drawXY();
});
function drawXY(){
x.domain([d3.min(cars, function(d) { return d.year; }), d3.max(cars, function(d) { return d.year; })]);
y.domain([d3.min(cars, function(d) { return d.power; }), d3.max(cars, function(d) { return d.power; })]);
var yPos = height -20;
chart.append("g")
.attr("class", "xaxis")
.attr("transform", "translate(0," + yPos + ")")
.call(xAxis);
chart.append("g")
.attr("class", "yaxis")
.attr("transform", "translate(50,0)")
.call(yAxis);
chart.selectAll(".dot")
.data(cars)
.enter().append("circle")
.attr("class", "dot")
.attr("cx", function(d) { return x(d.year); })
.attr("cy", function(d) { return y(d.power); })
.attr("r", 3);
}
d3.selectAll("circle").data(cars).enter()
.append("circle")
.classed("circle", true)
.on("mouseover", function() { d3.select(d3.event.target).classed("highlight", true); })
.on("mouseout", function() { d3.select(d3.event.target).classed("highlight", false); });
function type(d) {
d.economy = +d.economy; // coerce to number
d.displacement = +d.displacement; // coerce to number
d.power = +d.power; // coerce to number
d.weight = +d.weight; // coerce to number
d.year = +d.year;
return d;
}
})();
I am trying to create a corrologram using a set of data using D3.js.
I used R to create the correlation matrix but for visualization I want to use D3js and create a chart which shows the correlation matrix as in the picture. Can anyone guide me on this please.
Interesting problem so I took a whack at it. Using the mtcars dataset and given an R calculated correlation matrix, output in a CSV format using:
write.csv(cor(mtcars), file="data.csv")
Which creates:
"","mpg","cyl","disp","hp","drat","wt","qsec","vs","am","gear","carb"
"mpg",1,-0.852161959426613,-0.847551379262479,-0.776168371826586,0.681171907806749,-0.867659376517228,0.418684033921778,0.664038919127593,0.599832429454648,0.480284757338842,-0.550925073902459
"cyl",-0.852161959426613,1,0.902032872146999,0.83244745272182,-0.69993811382877,0.782495794463241,-0.591242073768869,-0.810811796083005,-0.522607046900675,-0.492686599389471,0.526988293749643
You can replicate your plot with d3:
d3.csv("data.csv", function(error, rows) {
// read in the CSV file and put the data in a d3 format or an array of objects
var data = [];
rows.forEach(function(d) {
var x = d[""]; // x represent the column name
delete d[""];
for (prop in d) {
var y = prop, // y is this row name
value = d[prop]; // correlation value
data.push({
x: x,
y: y,
value: +value
});
}
});
// standard d3 plot setup
var margin = {
top: 25,
right: 80,
bottom: 25,
left: 25
},
width = 500 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom,
domain = d3.set(data.map(function(d) { // our domain is just the column names
return d.x
})).values(),
num = Math.sqrt(data.length), // how many rows and columns
color = d3.scale.linear() // our color scale from red to white to blue
.domain([-1, 0, 1])
.range(["#B22222", "#fff", "#000080"]);
// set-up x and y scale
var x = d3.scale
.ordinal()
.rangePoints([0, width])
.domain(domain),
y = d3.scale
.ordinal()
.rangePoints([0, height])
.domain(domain),
xSpace = x.range()[1] - x.range()[0], // this is the space of each grid space
ySpace = y.range()[1] - y.range()[0];
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 + ")");
// bind our data for each grid space
var cor = svg.selectAll(".cor")
.data(data)
.enter()
.append("g")
.attr("class", "cor")
.attr("transform", function(d) {
return "translate(" + x(d.x) + "," + y(d.y) + ")";
});
// outer rectangle on each grid space
cor.append("rect")
.attr("width", xSpace)
.attr("height", ySpace)
.attr("x", -xSpace / 2)
.attr("y", -ySpace / 2)
// filter out below the diagonal
cor.filter(function(d){
var ypos = domain.indexOf(d.y);
var xpos = domain.indexOf(d.x);
for (var i = (ypos + 1); i < num; i++){
if (i === xpos) return false;
}
return true;
})
// append a text
.append("text")
.attr("y", 5)
.text(function(d) {
if (d.x === d.y) {
return d.x;
} else {
return d.value.toFixed(2);
}
})
// color it
.style("fill", function(d){
if (d.value === 1) {
return "#000";
} else {
return color(d.value);
}
});
// filter above the diagonal
cor.filter(function(d){
var ypos = domain.indexOf(d.y);
var xpos = domain.indexOf(d.x);
for (var i = (ypos + 1); i < num; i++){
if (i === xpos) return true;
}
return false;
})
// add a circle
.append("circle")
.attr("r", function(d){
return (width / (num * 2)) * (Math.abs(d.value) + 0.1);
})
.style("fill", function(d){
if (d.value === 1) {
return "#000";
} else {
return color(d.value);
}
});
// build the "yAxis" color scale
// its a series of rects colored correctly
// to produce a smooth gradient
var aS = d3.scale
.linear()
.range([-margin.top + 5, height + margin.bottom - 5])
.domain([1, -1]);
var yA = d3.svg.axis()
.orient("right")
.scale(aS)
.tickPadding(7);
var aG = svg.append("g")
.attr("class", "y axis")
.call(yA)
.attr("transform", "translate(" + (width + margin.right / 2) + " ,0)")
var iR = d3.range(-1, 1.01, 0.01);
var h = height / iR.length + 3;
iR.forEach(function(d){
aG.append('rect')
.style('fill',color(d))
.style('stroke-width', 0)
.style('stoke', 'none')
.attr('height', h)
.attr('width', 10)
.attr('x', 0)
.attr('y', aS(d))
});
});
Here's the result:
Full working code.
We can use d3 v4 here's the updated code with d3 changes' log.
I needed to code a simple app with a graph so I chose D3. I also use the ionic framework to code the app and I implemented all the code in a controller. It displays correct in the app. I know it's best practice to put this in a directive but I also had no luck on making that work.
But I have some trouble learning D3, I need to make a thermometer but I end up with a square. I followed tutorials and did my best. Can someone help me with this?
it needs to look something like this therometer
Code:
$scope.height = window.innerHeight - 110;
/**
* d3 code for the thermometer! d3 is a library for javascript and injected in the index.html in the www map.
*/
//this is an array for the chart is using for the rectangle in the chart itself. it gets it data form the ChallengeService
var bardata = [$scope.challenge.amount];
//this code is used to correctly show the axes of the chart.
var margin = {top: 30 , right: 30 , bottom: 40 , left: 50 };
// these are values needed to drawn the chart correctly $scope.height is the ion-view - header bar - footer bar.
var height = $scope.height - margin.top - margin.bottom,
width = 200 - margin.left - margin.right,
barWidth = 50,
barOffset = 5,
border = 5,
bordercolor = '#F5F5F5';
//used for the axis in scaling
var yScale = d3.scale.linear()
.domain([0, 2184])
.range([0, height]);
var xScale = d3.scale.ordinal()
.domain(d3.range(0, bardata.length))
.rangeBands([0, width])
//this is the actual chart that gets drawn.
var myChart = d3.select('#chart').append('svg')
.attr('width', width + margin.left + margin.right)
.attr('height', height + margin.top + margin.bottom)
.attr('id' , 'mijnsvg')
.append('g')
.attr('transform', 'translate(' +margin.left +','+margin.right +')')
.selectAll('rect').data(bardata)
.enter().append('rect')
.style('fill', '#d0e4db')
.attr('width', xScale.rangeBand())
.attr('x', function(d,i) {
return xScale(i);
})
//.attr('ry', 75)
.attr('height', 0)
.attr('y', height)
//if they want a border this is the way keep in mind that it will shrink the graph and you need to adjust it when drawing!
//.style("stroke", bordercolor)
//.style("stroke-width", border)
// used for how the chart is rendered this allows me to delay the drawing of the chart till the moment the users is on the tab.
myChart.transition()
.attr('height', function(d) {
return yScale(d);
})
.attr('y', function(d) {
return height - yScale(d);
})
.delay(function(d, i) {
return i * 50;
})
.duration(1300)
.ease('exp')
// theese are both axes being drawn
var vGuideScale1 = d3.scale.linear()
.domain([0, 2184])
.range([height, 0])
var vGuideScale2 = d3.scale.linear()
.domain([0, 2184])
.range([height, 0])
var vAxisLeft = d3.svg.axis()
.scale(vGuideScale1)
.orient('right')
.ticks(5)
.tickFormat(function(d){
return '€ ' + parseInt(d);
})
var vAxisRight = d3.svg.axis()
.scale(vGuideScale2)
.orient('right')
// i use this in d3 to draw the right line otherwise it will fill in values.
.ticks("")
var vGuide = d3.select('#mijnsvg').append('g')
vAxisLeft(vGuide)
vGuide.attr('transform', 'translate('+ margin.left+',' + margin.top+ ')')
vGuide.attr('rx', 50)
vGuide.selectAll('path')
.style({ fill: '#368169', stroke: "#368169"})
vGuide.selectAll('line')
.style({ stroke: "#368169"})
var vGuideRight = d3.select('#mijnsvg').append('g')
vAxisRight(vGuideRight)
vGuideRight.attr('transform', 'translate('+ 164.5 + ',' + margin.top +')' )
vGuideRight.selectAll('path')
.style({ fill: '#368169', stroke: "#368169"})
vGuideRight.selectAll('line')
.style({ stroke: "#368169"})
var hAxis = d3.svg.axis()
.scale(xScale)
.orient('top')
.tickValues('')
var hGuide = d3.select('#mijnsvg').append('g')
hAxis(hGuide)
hGuide.attr('transform', 'translate('+ margin.left+',' + margin.top + ')')
hGuide.selectAll('path')
.style({ fill: '#368169', stroke: "#368169"})
hGuide.selectAll('line')
.style({ stroke: "#368169"})
.style('xr', 100)
Instead of using rounded corner rect, I'd create a custom path generator:
function roundedRect(w, x, d) { // width of bar, x position and datum value
var arcHeight = 30; // height of arc
var p = "";
p += "M" + (x) + "," + (height); // move to lower left
p += " L" + (x) + "," + (yScale(d) + arcHeight); // line up to start of arc
p += " Q " + (w * 0.25) + "," + yScale(d) + " " + (w * 0.5 + x) + "," + yScale(d); // arc to center point
p += " Q " + (w * 0.75 + x) + "," + yScale(d) + " " + w + "," + (yScale(d) + arcHeight); // arc to end
p += " L" + w + "," + (height); // line down to bottom
return p;
}
You can use this to draw both the border and "bars".
Here's full working code. I cleaned up the axis a bit and added an attrTween function so you could still keep the animation.
<!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>
.axis path {
display: none;
}
.axis line {
stroke: #d0e4db;
}
line {
shape-rendering: crispEdges;
}
.axis .tick line {
stroke: #368169;
stroke-dasharray: 2, 2;
stroke-width: 4;
}
text {
font-family: Verdana;
font-size: 12px;
}
</style>
</head>
<body>
<div id="chart"></div>
<script>
var $scope = {};
$scope.height = 500;
/**
* d3 code for the thermometer! d3 is a library for javascript and injected in the index.html in the www map.
*/
//this is an array for the chart is using for the rectangle in the chart itself. it gets it data form the ChallengeService
var bardata = [1500];
//this code is used to correctly show the axes of the chart.
var margin = {
top: 30,
right: 30,
bottom: 5,
left: 50
};
// these are values needed to drawn the chart correctly $scope.height is the ion-view - header bar - footer bar.
var height = $scope.height - margin.top - margin.bottom,
width = 200 - margin.left - margin.right,
barWidth = 50,
barOffset = 5,
border = 5,
bordercolor = '#F5F5F5';
//used for the axis in scaling
var yScale = d3.scale.linear()
.domain([0, 2184])
.range([height, 0]);
var xScale = d3.scale.ordinal()
.domain(d3.range(0, bardata.length))
.rangeBands([0, width])
//this is the actual chart that gets drawn.
var svg = d3.select('#chart').append('svg')
.attr('width', width + margin.left + margin.right)
.attr('height', height + margin.top + margin.bottom)
.attr('id', 'mijnsvg')
.append('g')
.attr('transform', 'translate(' + margin.left + ',' + margin.right + ')');
var myChart = svg
.selectAll('rect').data(bardata)
.enter().append('path')
.style('fill', '#d0e4db');
// used for how the chart is rendered this allows me to delay the drawing of the chart till the moment the users is on the tab.
myChart.transition()
.attrTween("d", function(d) {
var interpolate = d3.interpolate(0, d);
return function(t) {
return roundedRect(xScale.rangeBand() - 15, 15, interpolate(t));
}
})
.delay(function(d, i) {
return i * 50;
})
.duration(1300)
.ease('exp');
var border = svg.append("g")
.append("path")
.attr("d", roundedRect(width, 0, 2184))
.style("stroke", "#368169")
.style("stroke-width", 6)
.style("fill", "none");
var yAxis = d3.svg.axis()
.scale(yScale)
.ticks(4)
.tickSize(width / 2)
.tickPadding(15)
.orient("left");
svg
.append("g")
.attr("transform","translate(" + width / 2 + ",0)")
.attr("class", "y axis")
.call(yAxis);
function roundedRect(w, x, d) {
var arcHeight = 30;
var p = "";
p += "M" + (x) + "," + (height);
p += " L" + (x) + "," + (yScale(d) + arcHeight);
p += " Q " + (w * 0.25 + x/2) + "," + yScale(d) + " " + (w * 0.5 + x/2) + "," + yScale(d);
p += " Q " + (w * 0.75 + x/2) + "," + yScale(d) + " " + w + "," + (yScale(d) + arcHeight);
p += " L" + w + "," + (height);
return p;
}
</script>
</body>
</html>
I have the javascript of the scatter d3.js library:
<!DOCTYPE html>
<meta charset="utf-8">
<style>
body {
font: 10px sans-serif;
}
.axis path, .axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.point {
fill: steelblue;
stroke: #000;
}
</style>
<body>
<script src="http://d3js.org/d3.v2.js?2.9.6"></script>
<script>
var margin = {top: 20, right: 20, bottom: 30, left: 40},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var x = d3.scale.linear()
.range([0, width]);
var y = d3.scale.linear()
.range([height, 0]);
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 + ")");
d3.csv("data.csv", function(data) {
// Coerce the strings to numbers.
data.forEach(function(d) {
d.x = +d.x;
d.y = +d.y;
});
// Compute the scales’ domains.
x.domain(d3.extent(data, function(d) { return d.x; })).nice();
y.domain(d3.extent(data, function(d) { return d.y; })).nice();
// Add the x-axis.
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(d3.svg.axis().scale(x).orient("bottom"));
// Add the y-axis.
svg.append("g")
.attr("class", "y axis")
.call(d3.svg.axis().scale(y).orient("left"));
// Add the points!
svg.selectAll(".point")
.data(data)
.enter().append("path")
.attr("class", "point")
.attr("d", d3.svg.symbol().type("triangle-up"))
.attr("transform", function(d) { return "translate(" + x(d.x) + "," + y(d.y) + ")"; });
});
</script>
The file:data.cvs
x,y
5,90
25,30
45,50
65,55
85,25
Instead of reading the data from a cvs file I added an array to the javascript and tried to extract x and y values directly from this array:
var rows = new array(
array(0,0),
array(90,90),
array(59,70),
array(65,77),
array(85,66)
);
How can I use the array rows in order to obtain the same result ??
You can use array of hash:
var data = [{"x":"5","y":"90"},{"x":"25","y":"30"},{"x":"45","y":"50"},
{"x":"65","y":"55"},{"x":"85","y":"25"}];
Or write a function to convert your array of arrays to this array of hash.
var rows = new Array(
Array(0,0),
Array(90,90),
Array(59,70),
Array(65,77),
Array(85,66)
);
for (var i = 0; i < rows.length; i++) {
data.push({x: rows[i][0], y: rows[i][1]});
}
// Coerce the strings to numbers.
data.forEach(function(d) {
d.x = +d.x;
d.y = +d.y;
});
Here's the live code:
http://vida.io/documents/THpmgQDARSWPJqGG5