score:7
The problem with your question has nothing to do with programming, or JavaScript, or D3... the problem is a basic dataviz concept (that's why I added the data-visualization tag in your question):
What you're trying to do is not correct! You should not use bars with a time scale. Time scales are for time series (in which we use dots, or dots connected by lines).
If you use bars with time in the x axis you'll face problems:
- Positioning the bar: the left margin of the bar will be always at the date you set. The whole bar will lie after that date;
- Setting the width of the bar: in a real bar chart, which uses categorical variables for the x axis, the width has no meaning. But in a time scale the width represents time.
However, just for the sake of explanation, let's create this bar chart with a time scale (despite the fact that this is a wrong choice)... Here is how to do it:
First, set the "width" of the bars in time. Let's say, each bar will have 10 days of width:
.attr("width", function(d){
return x(d3.timeDay.offset(d.date, 10)) - x(d.date)
})
Then, set the x
position of the bar to the current date less half its width (that is, less 5 days in our example):
.attr('x', function(d, i) {
return x(d3.timeDay.offset(d.date, -5));
})
Finally, don't forget to create a "padding" in the time scale:
var x = d3.scaleTime()
.domain([d3.min(data, function(d) {
return d3.timeDay.offset(d.date, -10);
}), d3.max(data, function(d) {
return d3.timeDay.offset(d.date, 10);
})])
.range([0, width]);
Here is your code with those changes:
var keys = [];
var legendKeys = [];
var maxVal = [];
var w = 800;
var h = 450;
var margin = {
top: 30,
bottom: 40,
left: 50,
right: 20,
};
var width = w - margin.left - margin.right;
var height = h - margin.top - margin.bottom;
var colors = ['#FF9A00', '#FFEBB6', '#FFC400', '#B4EDA0', '#FF4436'];
var data = [{
"one": 4306,
"two": 2465,
"three": 2299,
"four": 988,
"five": 554,
"six": 1841,
"date": "2015-05-31T00:00:00"
}, {
"one": 4378,
"two": 2457,
"three": 2348,
"four": 1021,
"five": 498,
"six": 1921,
"date": "2015-06-30T00:00:00"
}, {
"one": 3404,
"two": 2348,
"three": 1655,
"four": 809,
"five": 473,
"six": 1056,
"date": "2015-07-31T00:00:00"
},
];
data.forEach(function(d) {
d.date = new Date(d.date)
})
for (var i = 0; i < data.length; i++) {
for (var key in data[i]) {
if (!data.hasOwnProperty(key) && key !== "date")
maxVal.push(data[i][key]);
}
}
var x = d3.scaleTime()
.domain([d3.min(data, function(d) {
return d3.timeDay.offset(d.date, -10);
}), d3.max(data, function(d) {
return d3.timeDay.offset(d.date, 10);
})])
.range([0, width]);
var y = d3.scaleLinear()
.domain([0, d3.max(maxVal, function(d) {
return d;
})])
.range([height, 0]);
var svg = d3.select('body').append('svg')
.attr('class', 'chart')
.attr('width', w)
.attr('height', h);
var chart = svg.append('g')
.classed('graph', true)
.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
var layersArea = chart.append('g')
.attr('class', 'layers');
var layers = layersArea.append('g')
.attr('class', 'layer');
layers.selectAll('rect')
.data(data)
.enter()
.append('rect')
.attr('height', function(d, i) {
return height - y(d.one);
})
.attr('y', function(d, i) {
return y(d.one);
})
// .attr('width', function(d, i) {
// return 50;
// })
.attr("width", function(d) {
return x(d3.timeDay.offset(d.date, 10)) - x(d.date)
})
.attr('x', function(d, i) {
return x(d3.timeDay.offset(d.date, -5));
})
.style('fill', (d, i) => {
return colors[i];
});
chart.append('g')
.classed('x axis', true)
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x)
.tickFormat(d3.timeFormat("%Y-%m-%d")).tickValues(data.map(function(d) {
return new Date(d.date)
})));
chart.append('g')
.classed('y axis', true)
.call(d3.axisLeft(y)
.ticks(10));
<script src="https://d3js.org/d3.v4.min.js"></script>
Source: stackoverflow.com
Related Query
- How to use x and width in a bar chart with scaleTime?
- d3 bar chart with fixed bar width and fixed spacing to align in center axis line
- How can I use D3.js "onClick" event with an nvd3 bar when zoomed in on chart data?
- d3 bar chart with custom x axis and bar width
- NVD3 Line Plus Bar With Focus Chart only displaying half width of first and last bar
- D3 Bar Chart with Variable X and Y(variable width and height for bars)
- How can I create a basic bar chart with unique counts on the y axis and a category on the x axis?
- how to use getElementById with getBBox to determine the svg width and height
- How to use enter(), exit() and update with horizontal "stacked" chart
- How to use nest and rollup functions in D3 to create a bar chart
- How do I use event listeners to swtich my d3 bar chart where I only see one and not both?
- How can I set max value(range) for y-axis and bar width of a bar chart using nvd3.js
- How Do I relate and combine bar chart with bubble chart in D3?
- How to draw a Bar Chart with time on xAxis and one or more numeric data for yAxis in d3js?
- How to update d3.js bar chart with new data
- d3.js bar chart sorting: can't figure out how to sort x-axis labels along with bars
- d3.js stacked bar chart with positive and negative values
- How do I implement d3's enter update exit pattern for an area chart with focus and context?
- How to Make a bar chart with rounded corners with extended grid in d3.js?
- how to zoom d3.js chart and reload data with greater granularity (in AJAX)
- NVD3.js: Stacked and grouped bar chart with two y-axis
- D3 - How to loop through an object with keys for a bar chart
- how to use .scale and .translate with d3.js?
- Grouped bar chart with zoom and updateable data error
- Specifying Ticks on D3 Bar chart with Time Series data and scaleBand
- Trying to use D3 with React to create a bar chart
- How to line up x axis on stacked bar chart with a line overlay in d3.js
- Updating a bar chart with .update, .enter, and .exit?
- How to show values stacked bar chart utilizing dc.js and d3.js?
- D3 Bar and Linear Chart With Multiple Axis
More Query from same tag
- Clamp geodesic to min/max latitude with d3
- d3 library installed with npm doesn't load json file
- Redraw D3 Pie Chart with new data when clicking button or enter search field
- Combine Nodes & Links in D3 Force Graph After CSV is Parsed to make one Array (Angular & D3.JS)
- Range of brush dc.js d3.js
- D3 : Re-entrant table function
- Datamaps are showing small size map of India
- Network diagram
- D3.js Add a Shaded Timeframe Region Behind A Line on a Line Graph
- I want to create a Weibull probability Plot in Angular
- How to customize d3plus large tooltip
- Why do my svg nodes leak memory in IE
- d3js replica of nested line graph
- Retrieving keys from a json array file(dynamically) and use it for d3js functions
- Cartogram using angularjs and d3 TypeError: undefined is not a function
- Typescript d3(Power BI)
- D3.nest() looping through the keys
- How to rotate all text by x degree on x-axis in Javascript
- D3JS Petals / Flower Chart. How to adapt to use data
- Marimekko chart cell titles not updating
- D3 scale not mapping colors to values
- Create Multiple charts on dropdown with user inputs in d3js
- how to get margin of a div with it's outer html?
- Why isn't my updated data re-rendering?
- D3 svg click event and circle click event overlapping
- x position of tooltip in d3 stacked bar chart not working
- D3.js - show tick values on the Y axis
- Read a huge csv file and populate a Map in Javascript using d3
- Draw circles inside pie - d3 chart
- Zoom to bounding box without topoJSON