Related
I am working with D3.js and react-hooks to create charts, So I tried creating one Line chart by searching around and got one.
But the one I am working with is using Sample data, here in my case I have JSON data.
I have made the charts responsive as well using resize-observer-polyfill this library.
Now I am struggling to implement it with JSON data, to renders it with dynamic data.
What I did
const svgRef = useRef();
const wrapperRef = useRef();
const dimensions = useResizeObserver(wrapperRef); // for responsive
// will be called initially and on every data change
useEffect(() => {
const svg = select(svgRef.current);
const { width, height } =
dimensions || wrapperRef.current.getBoundingClientRect();
// scales + line generator
const xScale = scaleLinear()
.domain([0, data.length - 1]) // here I need to pass the data
.range([0, width]);
const yScale = scaleLinear()
.domain([0, max(data)])
.range([height, 0]);
const lineGenerator = line()
.x((d, index) => xScale(index))
.y((d) => yScale(d))
.curve(curveCardinal);
// render the line
svg
.selectAll('.myLine')
.data([data])
.join('path')
.attr('class', 'myLine')
.attr('stroke', 'black')
.attr('fill', 'none')
.attr('d', lineGenerator);
svg
.selectAll('.myDot')
.data(data)
.join('circle')
.attr('class', 'myDot')
.attr('stroke', 'black')
.attr('r', (value, index) => 4)
.attr('fill', (value, index) => 'red')
.attr('cx', (value, index) => xScale(index))
.attr('cy', yScale);
// axes
const xAxis = axisBottom(xScale);
svg
.select('.x-axis')
.attr('transform', `translate(0, ${height})`)
.call(xAxis);
const yAxis = axisLeft(yScale);
svg.select('.y-axis').call(yAxis);
}, [data, dimensions]);
<React.Fragment>
<div ref={wrapperRef} style={{ marginBottom: '2rem' }}>
<svg ref={svgRef}>
<g className="x-axis" />
<g className="y-axis" />
</svg>
</div>
</React.Fragment>
Here I am not able to pass the data, my data is below
[
{ anno: 2014, consumo: 300, color: "#ff99e6" },
{ anno: 2015, consumo: 290, color: "blue" },
{ anno: 2016, consumo: 295, color: "green" },
{ anno: 2017, consumo: 287, color: "yellow" },
{ anno: 2018, consumo: 282, color: "red" },
{ anno: 2019, consumo: 195, color: "white" }
]
Here in my data I have color for each data, which I want to show in each dot generated.
working code sandbox of line chart
Similarly I tried doing bar chart and it is working fine
I did some dynamic rendering to labels, when we resize the window the labels gets adjusted automatically.
Here is the full working bar chart what I am trying to implement to line chart
I have also commented the lines where I am doing what.
Edit / Update
I ahve been following #MGO 's answer and it helped me Alot, but still I am facing issue to align labels and filling the color to dots.
actually it is obvious that it will overlap because of the text size, but just to overcome that In bar chart I have used below code
const tickWidth = 40;
const width = xScaleLabels.range()[1];
const tickN = Math.floor(width / tickWidth);
const keepEveryNth = Math.ceil(xScaleLabels.domain().length / tickN);
const xScaleLabelDomain = xScaleLabels
.domain()
.filter((_, i) => i % keepEveryNth === 0);
xScaleLabels.domain(xScaleLabelDomain);
what it is doing is when the device size is small it will filter some labels and will not show labels.
And also I am using below code to give color
.attr("fill", ({ color }) => color)
But is is not taking any color, but it is taking by default black color.
I have data to show as label as July.9.2021 11:18:28 but I only want to show time so what I am doing in my bar chart code is below
const xScaleLabels = scaleBand()
.domain(
data.map(
({ sensorValueAddedTime }) => sensorValueAddedTime.split(' ')[2] // this I am using to show only time
)
)
.range([0, dimensions.width])
.padding(padding);
Same I am trying to do with Line chart, In a simple way, I do not want to change this to any time and all.
This is the second data, so basically the Answer I got is only working for 1st data not for second, I want that to be dynamic if data comes in any of these format I want to show.
sensorValueAddedTime I want to show on x-axis
sensorValue On y-axis
I have already added my bar chart full working code, Same I want to do with line chart.
[
{
sensorValue: 32,
sensorValueAddedTime: "July.9.2021 10:56:22",
color_code: null,
condition: null,
__typename: "sensorData"
},
{
sensorValue: 32,
sensorValueAddedTime: "July.9.2021 10:56:23",
color_code: null,
condition: null,
__typename: "sensorData"
},
{
sensorValue: 35,
sensorValueAddedTime: "July.9.2021 11:17:51",
color_code: null,
condition: null,
__typename: "sensorData"
},
{
sensorValue: 35,
sensorValueAddedTime: "July.9.2021 11:17:52",
color_code: null,
condition: null,
__typename: "sensorData"
},
{
sensorValue: 36,
sensorValueAddedTime: "July.9.2021 11:18:08",
color_code: null,
condition: null,
__typename: "sensorData"
},
{
sensorValue: 36,
sensorValueAddedTime: "July.9.2021 11:18:09",
color_code: null,
condition: null,
__typename: "sensorData"
},
{
sensorValue: 38,
sensorValueAddedTime: "July.9.2021 11:18:27",
condition: null,
color_code: null,
__typename: "sensorData"
},
{
sensorValue: 38,
sensorValueAddedTime: "July.9.2021 11:18:28",
condition: null,
color_code: null,
__typename: "sensorData"
}
]
In the original example from Muri's D3 with React Hooks video series data is a flat single-dimensional array: [10, 25, 30, 40, 25, 60].
In the new array you're providing (data1), we're asking D3 to render a chart based on an array of objects. So when we pass data1 in as a prop to our chart function, we need to do a little more work to access the values inside of our array of objects.
We'll need to scale the data values into the appropriate ranges. The original example looked up the values by their index in the array. We're going to need to access the values in the objects contained in the data1 array based on those objects' keys. Like this, to create our scales:
const yScale = scaleLinear()
.domain([0, max(data, (d) => d.sensorValue)])
.range([height, 0]);
// scale the values of sensorValueAddedTime into the range for our x axis values
// since it's a date you'll need to convert the strings to Date objects:
const xScale = scaleTime()
.domain([
new Date(min(data, (d) => d.sensorValueAddedTime)),
new Date(max(data, (d) => d.sensorValueAddedTime))
])
.range([0, width]);
And like this, in our lineGenerator function:
const lineGenerator = line()
.x((d) => xScale(new Date(d.sensorValueAddedTime))
.y((d) => yScale(d.sensorValue));
You'll notice above that if we're going to use scaleTime(), we'll have to convert sensorValueAddedTime into a value that D3 can make sense of -- right now there's an extra space in the string in your object, but if you strip that space you can convert to a Date object and use d3.scaleTime().
There's an updated, working Sandbox that's rendering this data to a line chart with additional comments here.
Update: OP was asking to plot a different set of data and asked that the points "appear in that order".
There's a different working Sandbox rendering this different set of data to a line chart correctly here.
It seems like what you're asking for -- the "line graph version of the bar chart" may not produce what you're after. Just talking it through:
If you use the index position of each object on your xScale, like this:
const xScale = scaleLinear()
.domain([0, data.length - 1])
.range([0, width]);
that will produce a pretty boring chart -- because you're saying "put a dot at every whole number representing the index of the array". In other words, a dot at 1, at 2, at 3, and so on.
For this chart, we should choose meaningful values in our data -- like data1.anno -- and use those to communicate.
For example:
Scaling the values into the range according to the index positions of the array and plotting them according to their index position, like this:
const xScale = scaleLinear()
.domain([0, data.length - 1])
.range([0, width]);
....chart code....
.attr("cx", (value, index) => xScale(index))
Produces this plot:
Solution
Scaling the values of the data into the range and plotting the points according to their values. We can use d3's extent method, like this:
const xScale = scaleLinear()
.domain(extent(data, (d) => d.anno))
.range([0, width]);
const yScale = scaleLinear()
.domain([0, max(data, (d) => d.consumo)])
.range([height, 0]);
....chart code...
.attr("cx", (value) => xScale(value.anno))
.attr("cy", (value) => yScale(value.consumo));
Produces this plot:
data1.anno is clearly a year. The option to parse the years as date obects is a good one. var parse = d3.timeParse("%Y"), then use this to set the domain of your time scale: .domain([parse(minDate), parse(maxDate)]), as shown here.
Otherwise, if you'd like to preserve that value on the x-axis and not treat it as a Date object, you can use Javascript's toFixed() method to remove the decimal places, remove the comma delimiter with d3.format and change the number of ticks that appear with axis.ticks().
That produces this chart:
To generate a line with these points, use the values in the data, not the indexes.
const lineGenerator = line()
// .x((d, index) => xScale(index)) // old
// .y((d) => yScale(d)) // old
.x((d) => xScale(d.anno)) // new
.y((d) => yScale(d.consumo)) // new
.curve(curveCardinal);
That produces this chart:
Finally, if your goal is to assign the color value in each object to a point, access those values and assign their values to the fill, like this:
.attr("fill", (value) => value.color)
That produces this chart:
Here's the working sandbox.
Hope this helps! ✌️
Suppose I have an array of values with corresponding dates, [{date: d1, value: v1}, ..., {date: dn, value: vn}], that I'd like to visualize using d3.js. As long as subsequent measurements are within a certain time range, for example not more than a week apart, I am happy with d3 interpolating between the measurements.
However, when subsequent records are farther apart, I don't want d3 to connect them. What would be the easiest way to achieve this?
Your question is not exactly clear: by "interpolate", I believe you mean "connecting the dots".
If you use a time scale for your x axis, D3 will automatically connect the dots for you and create a line (an SVG path element), regardless the time separation in the data points. But there is a way for making "gaps" in that line: using line.defined(). According to the API:
If defined is specified, sets the defined accessor to the specified function or boolean and returns this line generator.
The problem is, for this approach to work, you'll have to set a given value (let's say, null) in your dataset, between the dates in which you don't want to draw the line (that is, the dates that are not close enough, as you say in your question). You can do this manually or using a function.
This is a working demo: in my dataset, my data jumps from 7-Oct to 17-Oct (more than 1 week). So, I just created a null value in any date between these two (in my demo, 16-Oct). Then, in the line generator, the line jumps this null value, using defined:
d3.line().defined(function(d){return d.value != null;})
The result is that the line jumps from 7-Oct to 17-Oct:
var data = [{date: "1-Oct-16",value: 14},
{date: "2-Oct-16",value: 33},
{date: "3-Oct-16",value: 12},
{date: "4-Oct-16",value: 43},
{date: "5-Oct-16",value: 54},
{date: "6-Oct-16",value: 71},
{date: "7-Oct-16",value: 32},
{date: "16-Oct-16",value: null},
{date: "17-Oct-16",value: 54},
{date: "18-Oct-16",value: 14},
{date: "19-Oct-16",value: 34},
{date: "20-Oct-16",value: 32},
{date: "21-Oct-16",value: 56},
{date: "22-Oct-16",value: 24},
{date: "23-Oct-16",value: 42},
{date: "24-Oct-16",value: 52},
{date: "25-Oct-16",value: 66},
{date: "26-Oct-16",value: 34},
{date: "27-Oct-16",value: 62},
{date: "28-Oct-16",value: 48},
{date: "29-Oct-16",value: 51},
{date: "30-Oct-16",value: 42}];
var parseDate = d3.timeParse("%d-%b-%y");
data.forEach(function (d) {
d.date = parseDate(d.date);
});
var svg = d3.select("body")
.append("svg")
.attr("width", 500)
.attr("height", 200);
var xScale = d3.scaleTime().range([20, 480]);
var yScale = d3.scaleLinear().range([180, 10]);
xScale.domain(d3.extent(data, function (d) {
return d.date;
}));
yScale.domain([0, d3.max(data, function (d) {
return d.value;
})]);
var xAxis = d3.axisBottom(xScale).tickFormat(d3.timeFormat("%d"));
var yAxis = d3.axisLeft(yScale);
var baseline = d3.line()
.defined(function(d){return d.value != null;})
.x(function (d) {
return xScale(d.date);
})
.y(function (d) {
return yScale(d.value);
});
svg.append("path") // Add the valueline path.
.attr("d", baseline(data))
.attr("fill", "none")
.attr("stroke", "teal");
svg.append("g")
.attr("transform", "translate(0,180)")
.call(xAxis);
svg.append("g")
.attr("transform", "translate(20,0)")
.attr("class", "y axis")
.call(yAxis);
<script src="https://d3js.org/d3.v4.min.js"></script>
If you're trying to draw a broken line chart, then I don't think interpolation is what you're looking for. Building a custom SVG path is probably the way to go. See an example here:
https://bl.ocks.org/joeldouglass/1a0b2e855d2bedc24c63e396b04c8e36
Say I have an Array of these objects:
[
{name: "P1", Subj1: 9.7, Subj2: 10, Subj3: 9.5, Subj4: 8.2, Subj5:9.3, Subj6: 8.9},
{name: "P2", Subj1: 9.7, Subj2: 10, Subj3: 9.5, Subj4: 8.2, Subj5:9.3, Subj6: 8.9},
{name: "P3", Subj1: 9.7, Subj2: 10, Subj3: 9.5, Subj4: 8.2, Subj5:9.3, Subj6: 8.9} ]
I would like to plot a bar chart for one person. I currently have this code:
d3.select("#chart").selectAll("div.h-bar")
.data(getObj(name))
.enter()
.append("div")
.attr("class", "h-bar")
.append("span");
//delete elements not associated with data element
d3.select("#chart").selectAll("div.h-bar")
.data(getObj(name))
.exit().remove();
d3.select("#chart").selectAll("div.h-bar")
.data(getObj(name))
.attr("class", "h-bar")
.style("width", function (d) {
return ( d.Subj1* 10) + "px";
}
)
.select("span")
.text(function (d) {
return d.name;
});
with the getObj(name) function:
function getObj(Name){
for(var i = 0; i <studentList.length; i++){
if(studentList[i].Naam == Name){
console.log(studentList[i]);
return [studentList[i]];
}
}
}
I cant figure out how to get a bar chart for person 1 where every bar has a width of achieved note, and the span text the name of the subject.
Any hints?
My data array:
var data = [{glazed: 3.50, jelly: 4.50, powdered: 1.00, sprinkles: 3.50, age: 21, responses: 2,name:"test"},
{glazed: 2.83, jelly: 3.50, powdered: 1.83, sprinkles: 4.50, age: 22, responses: 6,name:"test"},
{glazed: 3.25, jelly: 4.75, powdered: 2.25, sprinkles: 3.50, age: 23, responses: 4,name:"test"},
{glazed: 1.50, jelly: 4.00, powdered: 2.50, sprinkles: 4.00, age: 25, responses: 2,name:"test"}];
If I wanted to find extent of either glazed or jelly or powdered or sprinkles to use for scaling, I would use a code as below..
var x = d3.scale.linear()
.domain(d3.extent(data, function (d) {
return d.glazed;//or jelly etc..
}))
.range([0, width]);
What would I need to do to get the extent of all values in glazed, jelly, powdered and sprinkles rather all values which are not age, responses and name.
This is because json file gets created dynamically and so I will have no idea of the key values except age, responses and name.
So, my requirement is that it should give me min as 1.5 (from glazed) and max as 4.75 (from jelly)
Any help is sincerely appreciated..
Thanks
var x = d3.scale.linear()
.domain(d3.extent(data.map(function (item) {
return (item.glazed);
})))
.range([0, width]);
map() returns [3.5, 2.83, 3.25, 1.5]
extent() returns [1.5, 3.5]
In case you need absolute minimum and maximum for all properties of the data, you should concatenate arrays:
var x = d3.scale.linear()
.domain(d3.extent(
[].concat(data.map(function (item) {
return (item.glazed);
}), data.map(function (item) {
return (item.jelly);
}), data.map(function (item) {
return (item.powdered);
}), data.map(function (item) {
return (item.sprinkles);
}))))
.range([0, width]);
Finally, if you have a list of valuable properties, you should replace [].concat(...) expression by anonymous function and call it immediately like this: function(array, names){...}(data, temp). You should know, in JavaScript array.property and array["property"] -- are the same calls.
var temp = ["glazed", "jelly", "powdered", "sprinkles"];
var width = 1000;
var data = [{glazed: 3.50, jelly: 4.50, powdered: 1.00, sprinkles: 3.50, age: 21, responses: 2,name:"test"},
{glazed: 2.83, jelly: 3.50, powdered: 1.83, sprinkles: 4.50, age: 22, responses: 6,name:"test"},
{glazed: 3.25, jelly: 4.75, powdered: 2.25, sprinkles: 3.50, age: 23, responses: 4,name:"test"},
{glazed: 1.50, jelly: 4.00, powdered: 2.50, sprinkles: 4.00, age: 25, responses: 2,name:"test"}];
var x = d3.scale.linear()
.domain(d3.extent(
function(array, names){
var res = [];
array.forEach(function(item){
names.forEach(function(name){
res = res.concat(item[name]);
});
});
return(res);
}(data, temp)
))
.range([0, width]);
DEMO: http://jsfiddle.net/v5qzuuhj/
Assuming that you want to be able to handle any key values except age, responses and name, and that others in addition to glazed, jellied, powdered & sprinkled might appear, this approach should work to calculate max and min values:
var keys_to_ignore = ["age", "responses", "name"]
data.forEach( function (row)
{
//Use d3.entries to create key\values
var data_entries = d3.entries(row)
// Add the 'current maximum' and 'current_min' based off the previous rows
// If this is the first row, the extent will be undefined
if (typeof extent !== "undefined") {
data_entries.push({"key":"current_max", "value":extent[1]})
data_entries.push({"key":"current_min", "value":extent[0]})
}
// now calculate the extent (max / min)
extent = d3.extent(data_entries, function (d) {
// Ignore specified keys
if (keys_to_ignore.indexOf(d.key) == -1) {
return d.value;
}
});
});
console.log(extent)
Using d3.entries will create objects with a key and value attribute, making the data easier to manage.
Working fiddle here: http://jsfiddle.net/henbox/aa4d0z81/
I feel like there's a more elegant way to do this, but I haven't managed to figure it out
I have the following array
var data = [
[{"time": 1, "value": 2.1}, {"time": 2, "value": 1.1}],{"time": 3, "value": 3.1}],
[{"time": 1, "value": 5.3}, {"time": 2, "value": 0.1}, {"time": 3, "value": 6.1}]
];
and I need to find the maximum time and value out of the entire array. the code that doesn't quite work is
var x = d3.scale.linear()
.domain([1, d3.max(data, function(d,i){ return d[i].time;})])
.range([0, width]);
for some reason I get a maximum time of 2, and not 3. even if I use a larger dataset with more point I still don't get the actual maximum value.
Any help is appreciated.
Your data is an array or arrays. If you want the "max of the maxes", you'll need to account for the nesting. One way to do it:
.domain([1, d3.max(data, function(arrayOfDs, i) {
return d3.max(arrayOfDs, function(d, i) { return d.time; });
})])