score:1
Accepted answer
Actually @rioV8 is right, you need to create each line by accessing the datapoint by key, and the keys need to be strings in this case.
Here is a running example with the following main changes:
- Changed the datapoints for more effect
- Renamed
values
to the more expressive nametopics
- Added a margin to the chart
- Corrected date matching pattern
- The axes need only be drawn once, the max y value is calculated by checking both topics. If you have more topics the logic needs little tweaking.
- During the actual rendering of the lines per topic the data needs to be scaled to the coordinate system.
File index.html
<!doctype html>
<html>
<head>
<title>nested bars</title>
<meta charset="utf-8">
<style>
svg.graphchart {
border: 1px solid gray;
background-color: lightyellow;
}
svg.graphchart text {
font-style: normal;
font-weight: normal;
font-family: monospace;
font-size: 10px;
stroke: none;
}
</style>
</head>
<body>
<svg class="graphchart" width="600" height="300"></svg>
</body>
<script src="node_modules/d3/dist/d3.js"></script>
<script src="./graphchart.js"></script>
</html>
File graphchart.js
/** Variables **/
// changed data for more effect
var data = [
{
"date": "23-10-2018 13:14:55",
"temperature": 8,
"humidity": 14
}, {
"date": "23-10-2018 13:15:25",
"temperature": 29,
"humidity": 2
}, {
"date": "23-10-2018 13:16:55",
"temperature": 10,
"humidity": 20
}
];
// which topics do we want to see
var topics = ['temperature', 'humidity'];
// svg specifics
var svg = d3.select('svg.graphchart');
// little margin
var margin = 40;
var width = svg.attr('width') - 2 * margin;
var height = svg.attr('height') - 2 * margin;
// the chart group
var chart = svg.append('g')
.attr('transform', `translate(${margin}, ${margin})`);
// some colors for the lines
var colors = d3.schemeAccent;
/** Helpers **/
// needed to adjust date pattern
var parseDate = d3.timeParse("%d-%m-%Y %H:%M:%S");
/** Axes: need only be drawn once **/
// x axis
var xScale = d3.scaleTime()
.domain(d3.extent(data, function(d){
var date = parseDate(d.date);
console.log(d.date);
return date;
}))
.range([0, width]);
var xAxis = d3.axisBottom(xScale)
.ticks(6)
.tickPadding(3)
.tickSize(10);
chart.append('g')
.attr('stroke', 'gray')
.attr('stroke-width', 1)
.attr('transform', `translate(0,${height})`)
.call(d3.axisBottom(xScale));
// y axis
var yScale = d3.scaleLinear()
.domain([ 0, d3.max(data, function(d){
return Math.max(d.temperature, d.humidity);
})])
.range([height, 0]);
var yAxis = d3.axisLeft(yScale)
.ticks(6)
.tickPadding(10)
.tickSize(10);
chart.append('g')
.attr('stroke', 'gray')
.attr('stroke-width', 1)
.call(yAxis);
/** render lines **/
// render one line
function renderLine(topic, color) {
var line = d3.line()
.x(function(d) { return xScale(parseDate(d.date)); })
.y(function(d) { return yScale(d[topic]); });
chart.append('path')
.datum(data)
.attr('stroke', color)
.attr('fill', 'none')
.attr('stroke-width', 2)
.attr('d', line);
}
// render each line
topics.forEach(function(topic, i) {
renderLine(topic, colors[i % colors.length]);
});
Anyway this is only one way to handle the task. The recommended way to getting acquainted with d3 is to check out the sound documentation and many examples at https://bl.ocks.org and play with it.
score:0
Use object indexing by string
var values = ["temperature","humidity"];
var y = d3.scaleLinear()
.domain([0,d3.max(data, d => d[value] )])
.range([height,0]);
var line = d3.line()
.x(d => x(parseDate(d.date)) )
.y(d => y(d[value]) );
Source: stackoverflow.com
Related Query
- D3 ... Best (recommended) way to load array of dictionaries with multiple Y values
- D3.js: Load flat 1-dimensional array via d3.csv results in "TypeError: groupData is undefined" / Load multiple CSV files with D3.js
- Get max value from array with multiple columns
- D3.js how to extract Y domain value from data array with multiple Y axis columns
- How to set multiple attributes with one value function?
- What's the easy way to load d3-selection-multi along with d3 v4 in RequireJS?
- Javascript: Array of dictionaries, get all key value pairs from one dictionairy with condition
- D3 : best way to find max value in a JSON object
- Best way to use selection.filter to get multiple selections
- how to add array of text to multiple divs with d3
- How to overcome x-axis styling problems when multiple X-axis Values with single point to load in C3 graph?
- Enter() statement with a function from one data array to multiple arrays? (Adding multiple Gradient Paths)
- Count number of items in an array of objects with a specific property value (JavaScript)
- Rearranging an array with key value
- What is the best way to combine multiple csv files data input using d3.csv in d3.json ?
- How to load multiple files with Queue.js and D3.js?
- d3 Grouping data on multiple values in combination with key value pair
- DRY way to stack multiple metrics with d3.layout.stack()
- How to create multiple pie charts with D3 from a single array with multiple objects?
- dc.js with crossfilter and d3, how to load multiple csv files at once, without knowing how many files the user will upload
- Load and parse multiple csv files with D3.js
- Load multiple SVGs into javascript array without DOM append
- How to load multiple csv files and use them mixed with each other
- Rollup returns undefined or array with value when using map
- D3 & Angular: What's the best way to resize multiple plots on window resize?
- Best way to center multiple geojson features in a small multiples chart
- A current recommended way to visualize data with AngularJS and D3.js
- What is the recommended way to refactor code written with d3.js like this?
- What is the best way to hide elements with a certain ID that doesn't effect the performance
- what's the best way to remove and adding div with D3?
More Query from same tag
- D3 mouseover effect for each chart on one page
- How do I update the y axis of the chart using D3 js
- How to use field value as a color value in vega lite pie chart?
- Add legend to chart with D3 V4 Angular-cli
- D3 javascript color from JSON attribute
- how to select brushX or brushY based on mouse direction in d3.js?
- Performing operations on substrings of text objects generated by D3
- Set a minimum height on bars in D3 graph
- d3v4 timeline adding a date axis to the bottom?
- D3.js: Position tooltips using element position, not mouse position?
- Can I force bubble size ratio in D3 Bubble charts?
- Set attribute of circle from another circle's attribute using d3.select?
- How to make a flat line in D3.js (version 3.x)
- how to Show text at fixed coordinate of (x,y) in Java Script D3
- d3js diagonal in tree layout
- How to draw spiral bubble charts with d3.js
- Hide the transformation of the graph in the beginning
- Set y-axis of d3 chart to fit widest label?
- Mouseenter event only firing once for d3.js svg circle
- Getting Cannot read property 'type' of null topojson
- Putting tspan inside rectangle D3JS SVG
- Strange D3 pan/zoom behaviour - accelerating pan
- Fisheye effect with force-directed graph : not taking effect until the graph settles
- force directed graph - width of link based on number of connections (volume) between nodes
- Getting Sankey diagram in D3 from csv file
- Acquire the data associated with a line in D3.js
- D3 triangle positioning to an exact point
- Objects in div connected dynamically using div ID
- Rollup js: how to make a closure like d3?
- Animated Ripples using jquery