I am creating an ordinal scale like so:
var x = d3.scale.ordinal()
.domain(["b1", "b2", "b3", "b4", "b5"])
.rangeBands([0, width], .1);
If I use this scale with an axis:
var xaxis = d3.svg.axis()
.scale(x)
.orient("bottom");
svg.append("g")
.attr("class", "axis")
.call(xaxis)
.attr("transform", "translate(" + 0 + "," + height + ")");
I find that when the axis is rendered in a bar chart with 5 bars, it tacks on numbers at the end. So I get:
b1,b2,b3,b4,b5,0,1,2,3,4.
Also the bars are not aligned to the ticks.
How do I make the axis behave so that I get b1,b2,b3,b4,b5 under the 5 bars ?
Here's the entire function:
function barchart_2d_array(width, height, barwidth, data, target_div){
var margin = {top: 20, right: 20, bottom: 30, left: 40},
w = width + margin.left + margin.right,
h = height + margin.top + margin.bottom;
var dataset = data;
values_arr=[];
for(var o in dataset){
values_arr.push(dataset[o]);
}
var x = d3.scale.ordinal()
.rangeBands([0, width], .1);
var y = d3.scale.linear()
.domain([0,d3.max(values_arr)])
.range([height,0]);
var svg = d3.select(target_div)
.append("svg")
.attr("width", w)
.attr("height", h)
.attr("style","border : 1px solid black")
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
x.domain(["b1", "b2", "b3", "b4", "b5"]);
window.x=x;
window.width=width;
svg.selectAll("rect")
.data(values_arr)
.enter()
.append("rect")
.attr("x",function(d,i){
return x(i);
})
.attr("y",function(d,i){
return y(d);
})
.attr("width",barwidth)
.attr("height",function(d,i){
return height - y(d);
});
var yaxis = d3.svg.axis()
.scale(y)
.orient("left")
.ticks(5);
var xaxis = d3.svg.axis()
.scale(x)
.orient("bottom");
svg.append("g")
.attr("class", "axis")
.call(yaxis);
svg.append("g")
.attr("class", "axis")
.call(xaxis)
.attr("transform", "translate(" + 0 + "," + height + ")");
};
This is how I call it:
<div id="bar_chart">
</div>
<script>
var dataset = { "b1":100, "b2":200, "b3":300, "b4":400, "b5":500 };
a = barchart_2d_array(400,200, 5,dataset,"#bar_chart");
</script>
D3's ordinal scales will implicitly add values into the domain if they haven't been seen before. Your code is passing in the additional values you're seeing in this function:
.attr("x",function(d,i){
return x(i);
})
i is the index of the node in the selection starting at 0.
You should take another look at the data set you're binding because I don't think it's doing what you want. You turn the data object into an array but in the process you're dropping the property names. Your array just contains the values ([100, 200, 300, 400, 500]), not the bar names that the x scale is expecting.
You probably want your array to look more like [{name: b1, value: 100}, {name: b2, value: 200}...] and then you can scale the data for x and y like this:
.attr("x",function(d) {
return x(d.name);
})
.attr("y",function(d) {
return y(d.value);
})
Once you get the shape of the bound data right everything else should fall into place.
Related
I am looking at an example on d3 svg bar chart (Example taken from Bar chart by modifying data)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<div id='Bar1'></div>
var tsv = "letter frequency\n" +
"django 12\n" +
"dictionary 33\n" +
"C 55\n" +
"D 100\n" +
"E 90\n" +
"F 320\n" +
"G 80\n" +
"H 10\n" +
"I 0\n" +
"J 0";
var margin1 = {top: 40, right: 20, bottom: 30, left: 40},
width1 = 460 //- margin.left - margin.right,
height1 = 200 //- margin.top - margin.bottom;
var formatPercent1 = d3.format("");
var x1 = d3.scale.ordinal()
.rangeRoundBands([0, width1], 0);
//.rangeRoundBands([width1, 0);
var y1 = d3.scale.linear()
.range([height1, 0]);
var xAxis1 = d3.svg.axis()
.scale(x1)
.orient("bottom");
var yAxis1 = d3.svg.axis()
.scale(y1)
.orient("left")
.tickFormat(formatPercent1);
var svg1 = d3.select("#Bar1").append("svg")
.attr("width", width1 + margin1.left + margin1.right)
.attr("height", height1 + margin1.top + margin1.bottom)
.append("g")
.attr("transform", "translate(" + margin1.left + "," + margin1.top + ")");
var data1 = d3.tsv.parse(tsv, type)
x1.domain(data1.map(function(d) { return d.letter; }));
y1.domain([0, d3.max(data1, function(d) { return d.frequency; })]);
svg1.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height1 + ")")
.call(xAxis1);
svg1.append("g")
.attr("class", "y axis")
.call(yAxis1)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Frequency");
svg1.selectAll(".bar")
.data(data1)
.enter().append("rect")
.attr("class", "bar")
.attr("x", function(d) { return x1(d.letter); })
.attr("width", x1.rangeBand())
.attr("y", function(d) { return y1(d.frequency); })
.attr("height", function(d) { return height1 - y1(d.frequency); })
function type(d) {
d.frequency = +d.frequency;
return d;
}
and the output of above code is as in the below image.
If we observe the bar represented by "F 320\n", its exceeding the y-axis value (where max value on y-axis is 300).
Can someone let me know if there is a possibility to show 320 on y axis so that bar represented by "F" will be shown without exceeding the Y-axis max value?
You can add a specific tick to your axis at the max value
// Get ticks
var ticks = y1.ticks();
// Add a tick at y max
ticks.push(d3.max(data1, function(d) { return d.frequency; }));
// Add all ticks to the y axis
var yAxis1 = d3.svg.axis()
.scale(y1)
.orient("left")
.tickFormat(formatPercent1)
.tickValues(ticks);
Or you can manually set all ticks:
// Add custom ticks to the y axis
var yAxis1 = d3.svg.axis()
.scale(y1)
.orient("left")
.tickFormat(formatPercent1)
.tickValues([80, 160, 240, 320]);
i have some values in my csv file and i show a graph with values on y axis and dates on x axis.
For first graph i have following values
date,close
13-Jul-16,0.8736701869033555
15-Jul-16,0.3631761567983922
17-Jul-16,0.4795564555162078
19-Jul-16,0.3754827857186281
21-Jul-16,0.4355941951068847
23-Jul-16,0.34393804366457353
25-Jul-16,0.40967947088135176
27-Jul-16,0.2707818657230363
29-Jul-16,0.34430251610420176
31-Jul-16,0.28089496856221585
For second graph i have following values
date,close
11-Jul-16,0.766705419439816
15-Jul-16,0.7353651170975812
17-Jul-16,0.41531502169603063
19-Jul-16,0.5927871032351933
21-Jul-16,0.7986419920511857
23-Jul-16,0.7904979990272231
25-Jul-16,0.817690401573838
27-Jul-16,0.8433545168648027
29-Jul-16,0.8612307965742473
31-Jul-16,0.806498303188971
But in second graph x axis does not contain all dates.. As an example i put a printscreen of my output graphs myoutput to here.
This is my code which takes datas from csv file and visualize it.
var selectedMonth=document.getElementById('selectedMonth').value;
var selectedTopic=document.getElementById('selectedTopic').value;
var userFileDirectory="../documents/";
userFileDirectory=userFileDirectory+selectedMonth+"/"+selectedTopic+"/"+"dataCs.csv";
// Set the dimensions of the canvas / graph
var margin = {top: 30, right: 20, bottom: 30, left: 50},
width = 600 - margin.left - margin.right,
height = 270 - margin.top - margin.bottom;
// Parse the date / time
var parseDate = d3.time.format("%d-%b-%y").parse;
// Set the ranges
var x = d3.time.scale().range([0, width]);
var y = d3.scale.linear().range([height, 0]);
// Define the axes
var xAxis = d3.svg.axis().scale(x)
.orient("bottom").ticks(5);
var yAxis = d3.svg.axis().scale(y)
.orient("left").ticks(5);
// Define the line
var valueline = d3.svg.line()
.x(function(d) { return x(d.date); })
.y(function(d) { return y(d.close); });
// Adds the svg canvas
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 + ")");
// Get the data
d3.csv(userFileDirectory, function(error, data) {
data.forEach(function(d) {
d.date = parseDate(d.date);
d.close = +d.close;
});
// Scale the range of the data
x.domain(d3.extent(data, function(d) { return d.date; }));
y.domain([0, d3.max(data, function(d) { return d.close; })]);
// Add the valueline path.
svg.append("path")
.attr("class", "line")
.attr("d", valueline(data));
// Add the X Axis
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
// Add the Y Axis
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
svg.append("text")
.text("("+selectedMonth+" "+selectedTopic+")");
});
I would try setting the tick values explicitly, using tickValues:
https://github.com/d3/d3-3.x-api-reference/blob/master/SVG-Axes.md#tickValues
ticks(5) will suggest 5 ticks, but will be adapted based on the scale's domain. Alternative to tickValues(), you could try ticks(d3.time.day, 2) to have a tick every 2 days.
The following code renders the axes on top of the graph and I can't seem to find where to add/subtract pixels to align the two.
I've spent weekend trying to solve this but I feel stuck. In my desperation, I've tried to add and subtract the padding in various places, add margins here and there to move things. It's like the graph and the axes are on two different scales but I can't see where I'm doing that either. This is a link to my codepen: http://codepen.io/piacoding/pen/amzoog?editors=0010
thank you,
var w = 780;
var h = 500;
var padding = 60;
var svg = d3.select("#graph")
.append("svg:svg")
.attr("width", w)
.attr("height", h )
.attr('class', 'gdp');
// define the x scale (horizontal)
var mindate = new Date(1947, 0, 1),
maxdate = new Date(2015, 6, 1);
var xScale = d3.time.scale()
.domain([mindate, maxdate])
.range([padding, w - padding]);
var maxnumber = d3.max(dataset, function(d) {
return d[1]
});
var yScale = d3.scale.linear()
.domain([0, maxnumber])
.range([0, h]);
var y = d3.scale.linear()
.domain([0, maxnumber])
.range([h - padding, padding]);
svg.selectAll("rect")
.data(dataset)
.enter()
.append("rect")
.attr("x", function(d, i) {
return i * (w / dataset.length);
})
.attr("y", function(d) {
return h - (yScale(d[1]));
})
.attr("width", w / dataset.length)
.attr("height", function(d) {
return yScale(d[1]);
})
// define the y axis
var yAxis = d3.svg.axis()
.orient("left")
.scale(y);
// define the y axis
var xAxis = d3.svg.axis()
.orient("bottom")
.scale(xScale);
// draw y axis
svg.append("g")
.attr("transform", "translate(" + padding + ",0)")
.attr('class', 'y axis')
.call(yAxis);
// draw x axis
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + (h - padding) + ")")
.call(xAxis);
Take a look at Margin Convention which does exactly what you need. See http://codepen.io/anon/pen/JRovxV?editors=0010 for the updated version:
var margin = {top: 20, right: 10, bottom: 60, left: 60};
var width = 780 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var svg = d3.select("#graph")
.append("svg:svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
.attr('class', 'gdp');
// define the x scale (horizontal)
var mindate = new Date(1947, 0, 1),
maxdate = new Date(2015, 6, 1);
// var firstDate = dataset[0];
// var lastDate = dataset[dataset.length - 1][0];
var xScale = d3.time.scale()
.domain([mindate, maxdate])
.range([0, width]);
var maxnumber = d3.max(dataset, function(d) {
return d[1]
});
var yScale = d3.scale.linear()
.domain([0, maxnumber])
.range([0, height]);
var y = d3.scale.linear()
.domain([0, maxnumber])
.range([height, 0]);
svg.selectAll("rect")
.data(dataset)
.enter()
.append("rect")
.attr("x", function(d, i) {
return i * (width / dataset.length);
})
.attr("y", function(d) {
return height - (yScale(d[1]));
})
.attr("width", width / dataset.length)
.attr("height", function(d) {
return yScale(d[1]);
})
// define the y axis
var yAxis = d3.svg.axis()
.orient("left")
.scale(y);
// define the y axis
var xAxis = d3.svg.axis()
.orient("bottom")
.scale(xScale);
// draw y axis
svg.append("g")
//.attr("transform", "translate(" + padding + ",0)")
.attr('class', 'y axis')
.call(yAxis);
// draw x axis
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
I've tried to make a simple line chart.
The x axis will show 10,100,1000 etc' values
For some reason I get all the values stacked on the left side of the x axis instead of spreading them equally on the axis.
var data = [
{views:10, odds: 56},
{views:100, odds: 64},
{views:1000, odds: 81},
{views:10000, odds: 95},
{views:100000, odds: 99},
{views:1000000, odds: 99},
{views:10000000, odds: 100},
];
// Set the dimensions of the canvas / graph
var margin = {top: 30, right: 20, bottom: 30, left: 50},
width = 600 - margin.left - margin.right,
height = 270 - margin.top - margin.bottom;
// Set the ranges
var x = d3.scale.linear()
.domain([
d3.min(data, function(d) { return d.views; }),
d3.max(data, function(d) { return d.views; })
])
.range([0, width]);
var y = d3.scale.linear()
.domain([
d3.min(data, function(d) { return d.odds; }),
d3.max(data, function(d) { return d.odds; })
])
.range([height, 0]);
// Define the axes
var xAxis = d3.svg.axis().scale(x)
.orient("bottom").ticks(7)
.tickValues(data.map((d)=>{ return d.views; }));
var yAxis = d3.svg.axis().scale(y)
.orient("left").ticks(7);
// Define the line
var valueline = d3.svg.line()
.x(function(d) { return x(d.views); })
.y(function(d) { return y(d.odds); });
// Adds the svg canvas
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 + ")");
// Add the valueline path.
svg.append("path")
.attr("class", "line")
.attr("d", valueline(data));
// Add the X Axis
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
// Add the Y Axis
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
https://jsfiddle.net/guy_l/77agq0hz/
This is the expected behaviour. They are not "stacked" on the left side, it's just a math problem: each value of x is just 10% of the next value! Keep in mind that your domain goes from 10 to 10 million, so the points would never be equally spread: 90% of your domain is just the space between the 6th and the 7th point.
You can change the scale for an ordinal one or, if you want to keep it quantitative, you need a logarithmic scale here:
d3.scale.log();
Check your updated fiddle: https://jsfiddle.net/gerardofurtado/v17cpqdk/
I am trying to use the hexbin layout with data that is normally distributed around 0 - all the examples use data centered around the center of the screen, so the scales are the same as the screen scales (except for y inversion)
I've tried to modify the scale functions to account for possible negative values. It works for the y-scale, but the x-scale gives NaNs, and the hexagons are plotted off the screen upper left. That is not the only problem - I would like to programmatically determine the bin size for the hexbin function - in my data series, all of the values are 'binned' into only one to three hexagons, and I need them spread out over the available domain.. here is my code
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="http://d3js.org/d3.hexbin.v0.min.js?5c6e4f0"></script>
<script>
minMultArray =function(arr,index){
var min = arr[0][index];
for (i=0;i<arr.length;i++) {
min = (min>arr[i][index]?arr[i][index]:min);
}
return min;
};
maxMultArray =function(arr,index){
var max = arr[0][index];
for (i=0;i<arr.length;i++) {
max = (max< arr[i][index]?arr[i][index]:max);
}
return max;
};
var margin = {top: 20, right: 20, bottom: 30, left: 40},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var randomX = d3.random.normal(0, 5),
randomY = d3.random.normal(0, 6),
points = d3.range(2000).map(function() { return [randomX(), randomY()]; });
var minX = minMultArray(points,0);
var minY = minMultArray(points,1);
//var minZ = minMultArray(points,2);
var maxX = maxMultArray(points,0);
var maxY = maxMultArray(points,1);
//var maxZ = maxMultArray(points,2);
var color = d3.scale.linear()
.domain([0, 20])
.range(["white", "steelblue"])
.interpolate(d3.interpolateLab);
var hexbin = d3.hexbin()
.size([width, height])
.radius(20);
alert('minX='+minX +' maxX='+maxX);
var x = d3.scale.linear()
.domain([minX, maxX])
.range(0,width);
alert('xScale(3)='+x(3));
var y = d3.scale.linear()
.domain([minY, maxY])
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.tickSize(6, -height);
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.tickSize(6, -width);
console.log('hex = ' +hexbin(points));
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 + ")");
svg.append("clipPath")
.attr("id", "clip")
.append("rect")
.attr("class", "mesh")
.attr("width", width)
.attr("height", height);
svg.append("g")
.attr("clip-path", "url(#clip)")
.selectAll(".hexagon")
.data(hexbin(points))
.enter().append("path")
.attr("class", "hexagon")
.attr("d", hexbin.hexagon())
.attr("transform", function(d) { return "translate(" + (d.x) + "," + (d.y) + ")"; })
.style("fill", function(d) { return color(d.length); });
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
</script>
After more debugging the hexbin functions, they are not compatible with negative and/or fractional domains- so I solved this by mapping my original data by linear scales up to the height and width of the hexagon plots. Then bin size is controlled by radius. I also modified the hexbin binning function to handle three element arrays, and can compute stats on the third element, using color or size to show mean/median/stddev/max/min. If interested, I can post the code on github...