Related
My code is as follows:
var data = [
{
name: "Canada",
values: [
{date: "2000", price: "200"},
{date: "2001", price: "120"},
{date: "2002", price: "33"},
{date: "2003", price: "21"},
{date: "2004", price: "51"},
{date: "2005", price: "190"},
{date: "2006", price: "120"},
{date: "2007", price: "85"},
{date: "2008", price: "221"},
{date: "2009", price: "101"}
]
},
{
name: "Maxico",
values: [
{date: "2000", price: "50"},
{date: "2001", price: "10"},
{date: "2002", price: "5"},
{date: "2003", price: "71"},
{date: "2004", price: "20"},
{date: "2005", price: "9"},
{date: "2006", price: "220"},
{date: "2007", price: "235"},
{date: "2008", price: "61"},
{date: "2009", price: "10"}
]
}
];
var width = 500;
var height = 300;
var margin = 50;
var duration = 250;
var lineOpacity = "0.25";
var lineOpacityHover = "0.85";
var otherLinesOpacityHover = "0.1";
var lineStroke = "1.5px";
var lineStrokeHover = "2.5px";
var circleOpacity = '0.85';
var circleOpacityOnLineHover = "0.25"
var circleRadius = 3;
var circleRadiusHover = 6;
/* Format Data */
var parseDate = d3.timeParse("%Y");
data.forEach(function(d) {
d.values.forEach(function(d) {
d.date = parseDate(d.date);
d.price = +d.price;
});
});
/* Scale */
var xScale = d3.scaleTime()
.domain(d3.extent(data[0].values, d => d.date))
.range([0, width-margin]);
var yScale = d3.scaleLinear()
.domain([0, d3.max(data[0].values, d => d.price)])
.range([height-margin, 0]);
var color = d3.scaleOrdinal(d3.schemeCategory10);
/* Add SVG */
var svg = d3.select("#chart").append("svg")
.attr("width", (width+margin)+"px")
.attr("height", (height+margin)+"px")
.append('g')
.attr("transform", `translate(${margin}, ${margin})`);
/* Add line into SVG */
var line = d3.line()
.x(d => xScale(d.date))
.y(d => yScale(d.price));
let lines = svg.append('g')
.attr('class', 'lines');
lines.selectAll('.line-group')
.data(data).enter()
.append('g')
.attr('class', 'line-group')
.on("mouseover", function(d, i) {
svg.append("text")
.attr("class", "title-text")
.style("fill", color(i))
.text(d.name)
.attr("text-anchor", "middle")
.attr("x", (width-margin)/2)
.attr("y", 5);
})
.on("mouseout", function(d) {
svg.select(".title-text").remove();
})
.append('path')
.attr('class', 'line')
.attr('d', d => line(d.values))
.style('stroke', (d, i) => color(i))
.style('opacity', lineOpacity)
.on("mouseover", function(d) {
d3.selectAll('.line')
.style('opacity', otherLinesOpacityHover);
d3.selectAll('.circle')
.style('opacity', circleOpacityOnLineHover);
d3.select(this)
.style('opacity', lineOpacityHover)
.style("stroke-width", lineStrokeHover)
.style("cursor", "pointer");
})
.on("mouseout", function(d) {
d3.selectAll(".line")
.style('opacity', lineOpacity);
d3.selectAll('.circle')
.style('opacity', circleOpacity);
d3.select(this)
.style("stroke-width", lineStroke)
.style("cursor", "none");
});
/* Add circles in the line */
lines.selectAll("circle-group")
.data(data).enter()
.append("g")
.style("fill", (d, i) => color(i))
.selectAll("circle")
.data(d => d.values).enter()
.append("g")
.attr("class", "circle")
.on("mouseover", function(d) {
d3.select(this)
.style("cursor", "pointer")
.append("text")
.attr("class", "text")
.text(`${d.price}`)
.attr("x", d => xScale(d.date) + 5)
.attr("y", d => yScale(d.price) - 10);
})
.on("mouseout", function(d) {
d3.select(this)
.style("cursor", "none")
.transition()
.duration(duration)
.selectAll(".text").remove();
})
.append("circle")
.attr("cx", d => xScale(d.date))
.attr("cy", d => yScale(d.price))
.attr("r", circleRadius)
.style('opacity', circleOpacity)
.on("mouseover", function(d) {
d3.select(this)
.transition()
.duration(duration)
.attr("r", circleRadiusHover);
})
.on("mouseout", function(d) {
d3.select(this)
.transition()
.duration(duration)
.attr("r", circleRadius);
});
/* Add Axis into SVG */
var xAxis = d3.axisBottom(xScale).ticks(5);
var yAxis = d3.axisLeft(yScale).ticks(5);
svg.append("g")
.attr("class", "x axis")
.attr("transform", `translate(0, ${height-margin})`)
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append('text')
.attr("y", 15)
.attr("transform", "rotate(-90)")
.attr("fill", "#000")
.text("Total values");
svg {
font-family: Sans-Serif, Arial;
}
.line {
stroke-width: 5;
fill: none;
}
.axis path {
stroke: black;
}
.text {
font-size: 12px;
}
.title-text {
font-size: 12px;
}
<html>
<head>
<script src="https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<div id="chart"></div>
</body>
</html>
My intention is to build a chart where the overlapping lines are colored based on the entry with the greater value in all portions of overlapping sections of the two lines.
If the blue line exceeds the yellow line at for any portion, that portion of should be coloured blue.
Similarly, if the yellow line exceeds the blue line at for any portion, that portion of should be coloured yellow.
For the above example, the following image is my intended output:
The first step is to remodel your data such that you will have an array that will contain objects of type: {name, price1, price2}
const areaData = [];
data[0].values.forEach((value, index) => {
areaData.push({date: value.date, price1: value.price, price2: data[1].values[index].price})
})
After that you will have to define 2 areas: one for the inner space between points (all area) and one that will fill only when line 2 points are above line 1
var innerArea = d3.area()
.x(d => xScale(d.date))
.y0(d => yScale(d.price2))
.y1(d => yScale(d.price1));
var line2PositiveArea = d3.area()
.x(d => xScale(d.date))
.y0(d => yScale(Math.min(d.price1, d.price2)))
.y1(d => yScale(d.price2));
having this you can define a clipping mask on your svg that will use to clip the positive filled area with inner area surface definition:
svg
.append('defs')
.append('mask')
.attr('id', 'hole')
.append('path')
.attr('d', d => innerArea(areaData))
.attr('fill', '#fff')
Then you can add your areas to the representation just above the line:
svg.append('path')
.attr('d', d => innerArea(areaData))
.attr('fill', (d, i) => color(i))
svg.append('path')
.attr('d', d => line2PositiveArea(areaData))
.attr('fill', (d, i) => color())
.attr('mask', 'url(#hole)');
Here is the full working js code
var data = [
{
name: "Canada",
values: [
{date: "2000", price: "200"},
{date: "2001", price: "120"},
{date: "2002", price: "33"},
{date: "2003", price: "21"},
{date: "2004", price: "51"},
{date: "2005", price: "190"},
{date: "2006", price: "120"},
{date: "2007", price: "85"},
{date: "2008", price: "221"},
{date: "2009", price: "101"}
]
},
{
name: "Maxico",
values: [
{date: "2000", price: "50"},
{date: "2001", price: "10"},
{date: "2002", price: "5"},
{date: "2003", price: "71"},
{date: "2004", price: "20"},
{date: "2005", price: "9"},
{date: "2006", price: "220"},
{date: "2007", price: "235"},
{date: "2008", price: "61"},
{date: "2009", price: "10"}
]
}
];
var width = 500;
var height = 300;
var margin = 50;
var duration = 250;
var lineOpacity = "0.25";
var lineOpacityHover = "0.85";
var otherLinesOpacityHover = "0.1";
var lineStroke = "1.5px";
var lineStrokeHover = "2.5px";
var circleOpacity = '0.85';
var circleOpacityOnLineHover = "0.25"
var circleRadius = 3;
var circleRadiusHover = 6;
/* Format Data */
var parseDate = d3.timeParse("%Y");
data.forEach(function(d) {
d.values.forEach(function(d) {
d.date = parseDate(d.date);
d.price = +d.price;
});
});
/* Scale */
var xScale = d3.scaleTime()
.domain(d3.extent(data[0].values, d => d.date))
.range([0, width-margin]);
var yScale = d3.scaleLinear()
.domain([0, d3.max(data[0].values, d => d.price)])
.range([height-margin, 0]);
var color = d3.scaleOrdinal(d3.schemeCategory10);
/* Add SVG */
var svg = d3.select("#chart").append("svg")
.attr("width", (width+margin)+"px")
.attr("height", (height+margin)+"px")
var innerArea = d3.area()
.x(d => xScale(d.date))
.y0(d => yScale(d.price2))
.y1(d => yScale(d.price1));
var line2PositiveArea = d3.area()
.x(d => xScale(d.date))
.y0(d => yScale(Math.min(d.price1, d.price2)))
.y1(d => yScale(d.price2));
const areaData = [];
data[0].values.forEach((value, index) => {
areaData.push({date: value.date, price1: value.price, price2: data[1].values[index].price})
})
svg.append('defs').append('mask').attr('id', 'hole').append('path').attr('d', d => innerArea(areaData)).attr('fill', '#fff')
svg = svg.append('g')
.attr("transform", `translate(${margin}, ${margin})`);
/* Add line into SVG */
var line = d3.line()
.x(d => xScale(d.date))
.y(d => yScale(d.price));
let lines = svg.append('g')
.attr('class', 'lines');
const linesGroup = lines.selectAll('.line-group')
.data(data).enter()
.append('g')
.attr('class', 'line-group')
.on("mouseover", function(d, i) {
svg.append("text")
.attr("class", "title-text")
.style("fill", color(i))
.text(d.name)
.attr("text-anchor", "middle")
.attr("x", (width-margin)/2)
.attr("y", 5);
})
.on("mouseout", function(d) {
svg.select(".title-text").remove();
})
svg.append('path')
.attr('d', d => innerArea(areaData))
.attr('fill', (d, i) => color(i))
svg.append('path')
.attr('d', d => line2PositiveArea(areaData))
.attr('fill', (d, i) => color())
.attr('mask', 'url(#hole)');
linesGroup.append('path')
.attr('class', 'line')
.attr('d', d => line(d.values))
.style('stroke', (d, i) => color(i))
.style('opacity', lineOpacity)
.on("mouseover", function(d) {
d3.selectAll('.line')
.style('opacity', otherLinesOpacityHover);
d3.selectAll('.circle')
.style('opacity', circleOpacityOnLineHover);
d3.select(this)
.style('opacity', lineOpacityHover)
.style("stroke-width", lineStrokeHover)
.style("cursor", "pointer");
})
.on("mouseout", function(d) {
d3.selectAll(".line")
.style('opacity', lineOpacity);
d3.selectAll('.circle')
.style('opacity', circleOpacity);
d3.select(this)
.style("stroke-width", lineStroke)
.style("cursor", "none");
});
/* Add circles in the line */
lines.selectAll("circle-group")
.data(data).enter()
.append("g")
.style("fill", (d, i) => color(i))
.selectAll("circle")
.data(d => d.values).enter()
.append("g")
.attr("class", "circle")
.on("mouseover", function(d) {
d3.select(this)
.style("cursor", "pointer")
.append("text")
.attr("class", "text")
.text(`${d.price}`)
.attr("x", d => xScale(d.date) + 5)
.attr("y", d => yScale(d.price) - 10);
})
.on("mouseout", function(d) {
d3.select(this)
.style("cursor", "none")
.transition()
.duration(duration)
.selectAll(".text").remove();
})
.append("circle")
.attr("cx", d => xScale(d.date))
.attr("cy", d => yScale(d.price))
.attr("r", circleRadius)
.style('opacity', circleOpacity)
.on("mouseover", function(d) {
d3.select(this)
.transition()
.duration(duration)
.attr("r", circleRadiusHover);
})
.on("mouseout", function(d) {
d3.select(this)
.transition()
.duration(duration)
.attr("r", circleRadius);
});
/* Add Axis into SVG */
var xAxis = d3.axisBottom(xScale).ticks(5);
var yAxis = d3.axisLeft(yScale).ticks(5);
svg.append("g")
.attr("class", "x axis")
.attr("transform", `translate(0, ${height-margin})`)
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append('text')
.attr("y", 15)
.attr("transform", "rotate(-90)")
.attr("fill", "#000")
.text("Total values");
I have a D3 line chart in my application and on hovering on the line a text is shown above the line displaying the line name. After that I had implemented a legend alongside with the chart and legend allows making lines appear and disappear upon clicking on legend item. My Sample code is given below. But now it has caused a problem like this. As now I'm setting the opacity of the line which was selected from legend to zero, the line gets disappeared. But if I hover in the area where the line was earlier still it shows the on hover text. Does anyone know a solution to avoid this problem.
You can see this issue by clicking on both items in the legend, Then all lines get disappeared. But if you move the mouse over the chart, where the lines were earlier, you will see that text will show on hovering
Example : https://jsfiddle.net/yasirunilan/ymavtsbj/4/
var data = [{
name: "USA",
values: [{
date: "2000",
price: "100"
},
{
date: "2001",
price: "110"
},
{
date: "2002",
price: "145"
},
{
date: "2003",
price: "241"
},
{
date: "2004",
price: "101"
},
{
date: "2005",
price: "90"
},
{
date: "2006",
price: "10"
},
{
date: "2007",
price: "35"
},
{
date: "2008",
price: "21"
},
{
date: "2009",
price: "201"
}
]
},
{
name: "Canada",
values: [{
date: "2000",
price: "100"
},
{
date: "2001",
price: "110"
},
{
date: "2002",
price: "145"
},
{
date: "2003",
price: "241"
},
{
date: "2004",
price: "101"
},
{
date: "2005",
price: "90"
},
{
date: "2006",
price: "10"
},
{
date: "2007",
price: "35"
},
{
date: "2008",
price: "21"
},
{
date: "2009",
price: "201"
}
]
}
];
var width = 500;
var height = 300;
var margin = 50;
var duration = 250;
var lineOpacity = "0.25";
var lineOpacityHover = "0.85";
var otherLinesOpacityHover = "0.1";
var lineStroke = "1.5px";
var lineStrokeHover = "2.5px";
var circleOpacity = '0.85';
var circleOpacityOnLineHover = "0.25"
var circleRadius = 3;
var circleRadiusHover = 6;
/* Format Data */
var parseDate = d3.timeParse("%Y");
data.forEach(function(d) {
d.values.forEach(function(d) {
d.date = parseDate(d.date);
d.price = +d.price;
});
});
/* Scale */
var xScale = d3.scaleTime()
.domain(d3.extent(data[0].values, d => d.date))
.range([0, width - margin]);
var yScale = d3.scaleLinear()
.domain([0, d3.max(data[0].values, d => d.price)])
.range([height - margin, 0]);
var color = d3.scaleOrdinal(d3.schemeCategory10);
/* Add SVG */
var svg = d3.select("#chart").append("svg")
.attr("width", (width + margin) + "px")
.attr("height", (height + margin) + "px")
.append('g')
.attr("transform", `translate(${margin}, ${margin})`);
/* Add line into SVG */
var line = d3.line()
.x(d => xScale(d.date))
.y(d => yScale(d.price));
let lines = svg.append('g')
.attr('class', 'lines');
lines.selectAll('.line-group')
.data(data).enter()
.append('g')
.attr('id', d => d.name.replace(/\s+/g, '') + "-line")
.attr('class', 'line-group')
.on("mouseover", function(d, i) {
svg.append("text")
.attr("class", "title-text")
.attr("font-weight", "bold")
.style("fill", color(i))
.text(d.name)
.attr("text-anchor", "middle")
.attr("x", (width - margin) / 2)
.attr("y", -30);
})
.on("mouseout", function(d) {
svg.select(".title-text").remove();
})
.append('path')
.attr('class', 'line')
.attr('d', d => line(d.values))
.style('stroke', d => color(d.name))
.style('opacity', lineOpacity)
.on("mouseover", function(d) {
d3.selectAll('.line')
.style('opacity', otherLinesOpacityHover);
d3.selectAll('.circle')
.style('opacity', circleOpacityOnLineHover);
d3.select(this)
.style('opacity', lineOpacityHover)
.style("stroke-width", lineStrokeHover)
.style("cursor", "pointer");
})
.on("mouseout", function(d) {
d3.selectAll(".line")
.style('opacity', lineOpacity);
d3.selectAll('.circle')
.style('opacity', circleOpacity);
d3.select(this)
.style("stroke-width", lineStroke)
.style("cursor", "none");
});
/* Add circles in the line */
lines.selectAll("circle-group")
.data(data).enter()
.append("g")
.attr('id', d => d.name.replace(/\s+/g, '') + "-circle")
.style("fill", d => color(d.name))
.selectAll("circle")
.data(d => d.values).enter()
.append("g")
.attr("class", "circle")
.on("mouseover", function(d) {
d3.select(this)
.style("cursor", "pointer")
.append("text")
.attr("class", "text")
.text(`${d.price}`)
.attr("x", d => xScale(d.date) + 5)
.attr("y", d => yScale(d.price) - 10);
})
.on("mouseout", function(d) {
d3.select(this)
.style("cursor", "none")
.transition()
.duration(duration)
.selectAll(".text").remove();
})
.append("circle")
.attr("cx", d => xScale(d.date))
.attr("cy", d => yScale(d.price))
.attr("r", circleRadius)
.style('opacity', circleOpacity)
.on("mouseover", function(d) {
d3.select(this)
.transition()
.duration(duration)
.attr("r", circleRadiusHover);
})
.on("mouseout", function(d) {
d3.select(this)
.transition()
.duration(duration)
.attr("r", circleRadius);
});
/* Add Axis into SVG */
var xAxis = d3.axisBottom(xScale).ticks(5);
var yAxis = d3.axisLeft(yScale).ticks(5);
svg.append("g")
.attr("class", "x axis")
.attr("transform", `translate(0, ${height-margin})`)
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append('text')
.attr("y", 15)
.attr("transform", "rotate(-90)")
.attr("fill", "#000")
.text("Total values");
var keys = []
// Add the Legend
var legend = d3.select("body").selectAll(".legend")
.data(data.map(d => d.name))
.enter().append("font")
.attr("class", "legend") // style the legend
.style("color", color)
.style("margin-left", 10 + "px")
.style("padding-left", 10 + "px")
.html(d => d)
d3.selectAll(".legend")
.on("click", function(d) {
keys.includes(d) ?
keys.splice(keys.indexOf(d), 1) :
keys.push(d)
d3.select(this).style("opacity", () => keys.includes(d) ? .5 : 1)
d3.select("#" + d.replace(/\s+/g, '') + "-line")
.transition().duration(100)
.style("opacity", () => keys.includes(d) ? 0 : 1);
d3.select("#" + d.replace(/\s+/g, '') + "-circle")
.transition().duration(100)
.style("opacity", () => keys.includes(d) ? 0 : 1);
})
You can set the CSS pointer-events to none in order to disable all mouse interactions and the set it to auto when you change the opacity back to 1 to enable them.
You can do it using this line:
.style("pointer-events", () => keys.includes(d) ? "none" : "auto");
Working demo: JsFiddle
Alternatively you can replace the lines that sets the opacity and the pointer-events by just setting the display css property like so:
.style("display", () => keys.includes(d) ? "none" : "inline");
Working demo: JsFiddle
I'm having a D3 v3 Multi Series line chart in my application and it works properly. But in a scenario where the data points for all series are equal, we can't identify the multiple lines because they are getting overlapped with each other. If all the data points are equal for three series, we can only see one single line instead of three lines. After getting some suggestions from developers I thought of going with a legend for the chart so that I can click the legend and see lines of the chart. Following is my sample code. Can someone help me to implement a legend with clickable behavior for it? Or else if there is any other solution for the problem they are also welcome.
Sample Code: https://jsfiddle.net/yasirunilan/rvoft1h8/
var data = [
{
name: "USA",
values: [
{date: "2000", price: "100"},
{date: "2001", price: "110"},
{date: "2002", price: "145"},
{date: "2003", price: "241"},
{date: "2004", price: "101"},
{date: "2005", price: "90"},
{date: "2006", price: "10"},
{date: "2007", price: "35"},
{date: "2008", price: "21"},
{date: "2009", price: "201"}
]
},
{
name: "Canada",
values: [
{date: "2000", price: "100"},
{date: "2001", price: "110"},
{date: "2002", price: "145"},
{date: "2003", price: "241"},
{date: "2004", price: "101"},
{date: "2005", price: "90"},
{date: "2006", price: "10"},
{date: "2007", price: "35"},
{date: "2008", price: "21"},
{date: "2009", price: "201"}
]
},
{
name: "Maxico",
values: [
{date: "2000", price: "100"},
{date: "2001", price: "110"},
{date: "2002", price: "145"},
{date: "2003", price: "241"},
{date: "2004", price: "101"},
{date: "2005", price: "90"},
{date: "2006", price: "10"},
{date: "2007", price: "35"},
{date: "2008", price: "21"},
{date: "2009", price: "201"}
]
}
];
var width = 500;
var height = 300;
var margin = 50;
var duration = 250;
var lineOpacity = "0.25";
var lineOpacityHover = "0.85";
var otherLinesOpacityHover = "0.1";
var lineStroke = "1.5px";
var lineStrokeHover = "2.5px";
var circleOpacity = '0.85';
var circleOpacityOnLineHover = "0.25"
var circleRadius = 3;
var circleRadiusHover = 6;
/* Format Data */
var parseDate = d3.timeParse("%Y");
data.forEach(function(d) {
d.values.forEach(function(d) {
d.date = parseDate(d.date);
d.price = +d.price;
});
});
/* Scale */
var xScale = d3.scaleTime()
.domain(d3.extent(data[0].values, d => d.date))
.range([0, width-margin]);
var yScale = d3.scaleLinear()
.domain([0, d3.max(data[0].values, d => d.price)])
.range([height-margin, 0]);
var color = d3.scaleOrdinal(d3.schemeCategory10);
/* Add SVG */
var svg = d3.select("#chart").append("svg")
.attr("width", (width+margin)+"px")
.attr("height", (height+margin)+"px")
.append('g')
.attr("transform", `translate(${margin}, ${margin})`);
/* Add line into SVG */
var line = d3.line()
.x(d => xScale(d.date))
.y(d => yScale(d.price));
let lines = svg.append('g')
.attr('class', 'lines');
lines.selectAll('.line-group')
.data(data).enter()
.append('g')
.attr('class', 'line-group')
.on("mouseover", function(d, i) {
svg.append("text")
.attr("class", "title-text")
.style("fill", color(i))
.text(d.name)
.attr("text-anchor", "middle")
.attr("x", (width-margin)/2)
.attr("y", 5);
})
.on("mouseout", function(d) {
svg.select(".title-text").remove();
})
.append('path')
.attr('class', 'line')
.attr('d', d => line(d.values))
.style('stroke', (d, i) => color(i))
.style('opacity', lineOpacity)
.on("mouseover", function(d) {
d3.selectAll('.line')
.style('opacity', otherLinesOpacityHover);
d3.selectAll('.circle')
.style('opacity', circleOpacityOnLineHover);
d3.select(this)
.style('opacity', lineOpacityHover)
.style("stroke-width", lineStrokeHover)
.style("cursor", "pointer");
})
.on("mouseout", function(d) {
d3.selectAll(".line")
.style('opacity', lineOpacity);
d3.selectAll('.circle')
.style('opacity', circleOpacity);
d3.select(this)
.style("stroke-width", lineStroke)
.style("cursor", "none");
});
/* Add circles in the line */
lines.selectAll("circle-group")
.data(data).enter()
.append("g")
.style("fill", (d, i) => color(i))
.selectAll("circle")
.data(d => d.values).enter()
.append("g")
.attr("class", "circle")
.on("mouseover", function(d) {
d3.select(this)
.style("cursor", "pointer")
.append("text")
.attr("class", "text")
.text(`${d.price}`)
.attr("x", d => xScale(d.date) + 5)
.attr("y", d => yScale(d.price) - 10);
})
.on("mouseout", function(d) {
d3.select(this)
.style("cursor", "none")
.transition()
.duration(duration)
.selectAll(".text").remove();
})
.append("circle")
.attr("cx", d => xScale(d.date))
.attr("cy", d => yScale(d.price))
.attr("r", circleRadius)
.style('opacity', circleOpacity)
.on("mouseover", function(d) {
d3.select(this)
.transition()
.duration(duration)
.attr("r", circleRadiusHover);
})
.on("mouseout", function(d) {
d3.select(this)
.transition()
.duration(duration)
.attr("r", circleRadius);
});
/* Add Axis into SVG */
var xAxis = d3.axisBottom(xScale).ticks(5);
var yAxis = d3.axisLeft(yScale).ticks(5);
svg.append("g")
.attr("class", "x axis")
.attr("transform", `translate(0, ${height-margin})`)
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append('text')
.attr("y", 15)
.attr("transform", "rotate(-90)")
.attr("fill", "#000")
.text("Total values");
I'm posting the solution that I used.
https://jsfiddle.net/yasirunilan/rvoft1h8/7/
var data = [{
name: "USA",
values: [{
date: "2000",
price: "100"
},
{
date: "2001",
price: "110"
},
{
date: "2002",
price: "145"
},
{
date: "2003",
price: "241"
},
{
date: "2004",
price: "101"
},
{
date: "2005",
price: "90"
},
{
date: "2006",
price: "10"
},
{
date: "2007",
price: "35"
},
{
date: "2008",
price: "21"
},
{
date: "2009",
price: "201"
}
]
},
{
name: "Canada",
values: [{
date: "2000",
price: "100"
},
{
date: "2001",
price: "110"
},
{
date: "2002",
price: "145"
},
{
date: "2003",
price: "241"
},
{
date: "2004",
price: "101"
},
{
date: "2005",
price: "90"
},
{
date: "2006",
price: "10"
},
{
date: "2007",
price: "35"
},
{
date: "2008",
price: "21"
},
{
date: "2009",
price: "201"
}
]
},
{
name: "Maxico",
values: [{
date: "2000",
price: "100"
},
{
date: "2001",
price: "110"
},
{
date: "2002",
price: "145"
},
{
date: "2003",
price: "241"
},
{
date: "2004",
price: "101"
},
{
date: "2005",
price: "90"
},
{
date: "2006",
price: "10"
},
{
date: "2007",
price: "35"
},
{
date: "2008",
price: "21"
},
{
date: "2009",
price: "201"
}
]
}
];
var width = 500;
var height = 300;
var margin = 50;
var duration = 250;
var lineOpacity = "0.25";
var lineOpacityHover = "0.85";
var otherLinesOpacityHover = "0.1";
var lineStroke = "1.5px";
var lineStrokeHover = "2.5px";
var circleOpacity = '0.85';
var circleOpacityOnLineHover = "0.25"
var circleRadius = 3;
var circleRadiusHover = 6;
/* Format Data */
var parseDate = d3.timeParse("%Y");
data.forEach(function(d) {
d.values.forEach(function(d) {
d.date = parseDate(d.date);
d.price = +d.price;
});
});
/* Scale */
var xScale = d3.scaleTime()
.domain(d3.extent(data[0].values, d => d.date))
.range([0, width - margin]);
var yScale = d3.scaleLinear()
.domain([0, d3.max(data[0].values, d => d.price)])
.range([height - margin, 0]);
var color = d3.scaleOrdinal(d3.schemeCategory10);
/* Add SVG */
var svg = d3.select("#chart").append("svg")
.attr("width", (width + margin) + "px")
.attr("height", (height + margin) + "px")
.append('g')
.attr("transform", `translate(${margin}, ${margin})`);
/* Add line into SVG */
var line = d3.line()
.x(d => xScale(d.date))
.y(d => yScale(d.price));
let lines = svg.append('g')
.attr('class', 'lines');
lines.selectAll('.line-group')
.data(data).enter()
.append('g')
.attr('id',function(d){ return d.name.replace(/\s+/g, '')+"-line"; })
.attr('class', 'line-group')
.on("mouseover", function(d, i) {
svg.append("text")
.attr("class", "title-text")
.style("fill", color(i))
.text(d.name)
.attr("text-anchor", "middle")
.attr("x", (width - margin) / 2)
.attr("y", 5);
})
.on("mouseout", function(d) {
svg.select(".title-text").remove();
})
.append('path')
.attr('class', 'line')
.attr('d', d => line(d.values))
.style('stroke', (d, i) => color(i))
.style('opacity', lineOpacity)
.on("mouseover", function(d) {
d3.selectAll('.line')
.style('opacity', otherLinesOpacityHover);
d3.selectAll('.circle')
.style('opacity', circleOpacityOnLineHover);
d3.select(this)
.style('opacity', lineOpacityHover)
.style("stroke-width", lineStrokeHover)
.style("cursor", "pointer");
})
.on("mouseout", function(d) {
d3.selectAll(".line")
.style('opacity', lineOpacity);
d3.selectAll('.circle')
.style('opacity', circleOpacity);
d3.select(this)
.style("stroke-width", lineStroke)
.style("cursor", "none");
});
/* Add circles in the line */
lines.selectAll("circle-group")
.data(data).enter()
.append("g")
.attr('id',function(d){ return d.name.replace(/\s+/g, '')+"-circle"; })
.style("fill", (d, i) => color(i))
.selectAll("circle")
.data(d => d.values).enter()
.append("g")
.attr("class", "circle")
.on("mouseover", function(d) {
d3.select(this)
.style("cursor", "pointer")
.append("text")
.attr("class", "text")
.text(`${d.price}`)
.attr("x", d => xScale(d.date) + 5)
.attr("y", d => yScale(d.price) - 10);
})
.on("mouseout", function(d) {
d3.select(this)
.style("cursor", "none")
.transition()
.duration(duration)
.selectAll(".text").remove();
})
.append("circle")
.attr("cx", d => xScale(d.date))
.attr("cy", d => yScale(d.price))
.attr("r", circleRadius)
.style('opacity', circleOpacity)
.on("mouseover", function(d) {
d3.select(this)
.transition()
.duration(duration)
.attr("r", circleRadiusHover);
})
.on("mouseout", function(d) {
d3.select(this)
.transition()
.duration(duration)
.attr("r", circleRadius);
});
/* Add Axis into SVG */
var xAxis = d3.axisBottom(xScale).ticks(5);
var yAxis = d3.axisLeft(yScale).ticks(5);
svg.append("g")
.attr("class", "x axis")
.attr("transform", `translate(0, ${height-margin})`)
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append('text')
.attr("y", 15)
.attr("transform", "rotate(-90)")
.attr("fill", "#000")
.text("Total values");
var dataNest = d3.nest()
.key(function(d) {
return d.name;
})
.entries(data);
var legendSpace = width / dataNest.length;
// Loop through each symbol / key
dataNest.forEach(function(d, i) {
// Add the Legend
svg.append("text")
.attr("x", (legendSpace / 2) + i * legendSpace) // space legend
.attr("y", height)
.attr("class", "legend") // style the legend
.style("fill", color(i))
.on("click", function() {
// Determine if current line is visible
var active = d.active ? false : true,
newOpacity = active ? 0 : 1;
// Hide or show the elements based on the ID
d3.select("#" + d.key.replace(/\s+/g, '') + "-line")
.transition().duration(100)
.style("opacity", newOpacity);
d3.select("#" + d.key.replace(/\s+/g, '') + "-circle")
.transition().duration(100)
.style("opacity", newOpacity);
// Update whether or not the elements are active
d.active = active;
})
.text(d.key);
});
Im new to JS and HTML so I am having a hard time implementing this change:
I want the values of the stacked bar graph to always be displayed rather than being dependent of the mouseover.
How would I go about changing the below code to achieve this?
var margin = {top: 20, right: 160, bottom: 35, left: 30};
var width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
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 + ")");
/* Data in strings like it would be if imported from a csv */
var data = [
{ year: "2006", redDelicious: "10", mcintosh: "15", oranges: "9", pears: "6" },
{ year: "2007", redDelicious: "12", mcintosh: "18", oranges: "9", pears: "4" },
{ year: "2008", redDelicious: "05", mcintosh: "20", oranges: "8", pears: "2" },
{ year: "2009", redDelicious: "01", mcintosh: "15", oranges: "5", pears: "4" },
{ year: "2010", redDelicious: "02", mcintosh: "10", oranges: "4", pears: "2" },
{ year: "2011", redDelicious: "03", mcintosh: "12", oranges: "6", pears: "3" },
{ year: "2012", redDelicious: "04", mcintosh: "15", oranges: "8", pears: "1" },
{ year: "2013", redDelicious: "06", mcintosh: "11", oranges: "9", pears: "4" },
{ year: "2014", redDelicious: "10", mcintosh: "13", oranges: "9", pears: "5" },
{ year: "2015", redDelicious: "16", mcintosh: "19", oranges: "6", pears: "9" },
{ year: "2016", redDelicious: "19", mcintosh: "17", oranges: "5", pears: "7" },
];
var parse = d3.time.format("%Y").parse;
// Transpose the data into layers
var dataset = d3.layout.stack()(["redDelicious", "mcintosh", "oranges", "pears"].map(function(fruit) {
return data.map(function(d) {
return {x: parse(d.year), y: +d[fruit]};
});
}));
// Set x, y and colors
var x = d3.scale.ordinal()
.domain(dataset[0].map(function(d) { return d.x; }))
.rangeRoundBands([10, width-10], 0.02);
var y = d3.scale.linear()
.domain([0, d3.max(dataset, function(d) { return d3.max(d, function(d) { return d.y0 + d.y; }); })])
.range([height, 0]);
var colors = ["b33040", "#d25c4d", "#f2b447", "#d9d574"];
// Define and draw axes
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.ticks(5)
.tickSize(-width, 0, 0)
.tickFormat( function(d) { return d } );
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.tickFormat(d3.time.format("%Y"));
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
// Create groups for each series, rects for each segment
var groups = svg.selectAll("g.cost")
.data(dataset)
.enter().append("g")
.attr("class", "cost")
.style("fill", function(d, i) { return colors[i]; });
var rect = groups.selectAll("rect")
.data(function(d) { return d; })
.enter()
.append("rect")
.attr("x", function(d) { return x(d.x); })
.attr("y", function(d) { return y(d.y0 + d.y); })
.attr("height", function(d) { return y(d.y0) - y(d.y0 + d.y); })
.attr("width", x.rangeBand())
.on("mouseover", function() { tooltip.style("display", null); })
.on("mouseout", function() { tooltip.style("display", "none"); })
.on("mousemove", function(d) {
var xPosition = d3.mouse(this)[0] - 15;
var yPosition = d3.mouse(this)[1] - 25;
tooltip.attr("transform", "translate(" + xPosition + "," + yPosition + ")");
tooltip.select("text").text(d.y);
});
// Draw legend
var legend = svg.selectAll(".legend")
.data(colors)
.enter().append("g")
.attr("class", "legend")
.attr("transform", function(d, i) { return "translate(30," + i * 19 + ")"; });
legend.append("rect")
.attr("x", width - 18)
.attr("width", 18)
.attr("height", 18)
.style("fill", function(d, i) {return colors.slice().reverse()[i];});
legend.append("text")
.attr("x", width + 5)
.attr("y", 9)
.attr("dy", ".35em")
.style("text-anchor", "start")
.text(function(d, i) {
switch (i) {
case 0: return "Anjou pears";
case 1: return "Naval oranges";
case 2: return "McIntosh apples";
case 3: return "Red Delicious apples";
}
});
// Prep the tooltip bits, initial display is hidden
var tooltip = svg.append("g")
.attr("class", "tooltip")
.style("display", "none");
tooltip.append("rect")
.attr("width", 30)
.attr("height", 20)
.attr("fill", "white")
.style("opacity", 0.5);
tooltip.append("text")
.attr("x", 15)
.attr("dy", "1.2em")
.style("text-anchor", "middle")
.attr("font-size", "12px")
.attr("font-weight", "bold");
svg {
font: 10px sans-serif;
shape-rendering: crispEdges;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
}
path.domain {
stroke: none;
}
.y .tick line {
stroke: #ddd;
}
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
I guess you need to add a label (tooltip) for each rect result. With little calculations I've got this:
http://jsfiddle.net/5o4jefap/87/
Here is the modified part without mouse events attached:
var rect = groups.selectAll("rect")
.data(function(d) { return d; })
.enter()
.append("g")
.attr('class', 'tooltip')
.append('rect')
.attr("x", function(d) { return x(d.x); })
.attr("y", function(d) { return y(d.y0 + d.y); })
.attr("height", function(d) { return y(d.y0) - y(d.y0 + d.y); })
.attr("width", x.rangeBand())
groups.selectAll('.tooltip')
.append("rect")
.attr('width', 15)
.attr('height', 15)
.attr('fill', 'white')
.style("opacity", 0.5)
.attr('y', function(d) {
var rectY = y(d.y0 + d.y),
rectHalfHeight = ((y(d.y0) - y(d.y0 + d.y)) / 2),
tooltipHalfHeight = (this.getBBox().height / 2);
return rectY + rectHalfHeight - tooltipHalfHeight;
})
.attr("x", function(d) {
var rectX = x(d.x),
rectHalfWidth = (x.rangeBand() / 2),
tooltipHalfWidth = (this.getBBox().width / 2);
return rectX + rectHalfWidth - tooltipHalfWidth;
})
groups.selectAll('.tooltip')
.append('text')
.attr("x", function(d) {
var rectX = x(d.x),
rectHalfWidth = (x.rangeBand() / 2),
tooltipHalfWidth = (this.getBBox().width / 2);
return rectX + rectHalfWidth - tooltipHalfWidth;
})
.attr("y", function(d) {
var rectY = y(d.y0 + d.y),
rectHalfHeight = ((y(d.y0) - y(d.y0 + d.y)) / 2),
tooltipHalfHeight = (this.getBBox().height / 2);
return rectY + rectHalfHeight - tooltipHalfHeight;
})
.attr("dy", '5px')
.style("text-anchor", "middle")
.attr("font-size", "12px")
.attr("font-weight", "bold")
.text(function (data) {
return data.y;
} );
I need to plot bubble chart, where each bubble is a donut chart like in below image in d3 version 3. I am able to achieve something, but don't understand how to distribute the circles horizontally, as my widget will be rectangular.
Also, how to make the donut bubble like in the image below. Any help would be appreciated. Thanks.
Code:
let colorCircles = {
'a': '#59bcf9',
'b': '#faabab',
'd': '#ffde85'
};
let tooltip = d3.select("body")
.append("div")
.attr("class", "tooltip-inner")
.style("position", "absolute")
.style("min-width", "12rem")
.style("visibility", "hidden")
.style("color", "#627386")
.style("padding", "15px")
.style("stroke", '#b8bfca')
.style("fill", "none")
.style("stroke-width", 1)
.style("background-color", "#fff")
.style("border-radius", "6px")
.style("text-align", "center")
.text("");
let bubble = d3.layout.pack()
.sort(null)
.size([width, diameter])
.padding(15)
.value(function(d) {
return d[columnForRadius];
});
let svg = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", diameter)
.attr("class", "bubble");
let nodes = bubble.nodes({
children: dataset
}).filter(function(d) {
return !d.children;
});
let circles = svg.selectAll("circle")
.data(nodes)
.enter()
.append("circle")
.attr("r", function(d) {
return d.r;
})
.attr("cx", function(d) {
return d.x;
})
.attr("cy", function(d) {
return d.y - 20;
})
.style("fill", function(d) {
return colorCircles[d[columnForColors]]
})
.on("mouseover", function(d) {
tooltip.style("visibility", "visible");
tooltip.html('<p>' + d[columnForColors] + ": " + d[columnForText] + "</p><div class='font-bold displayInlineBlock'> $" + d[columnForRadius] + '</div>');
})
.on("mousemove", function() {
return tooltip.style("top", (d3.event.offsetY - 10) + "px").style("left", (d3.event.offsetX + 10) + "px");
})
// .on("mouseout", function() {
// return tooltip.style("visibility", "hidden");
// })
.attr("class", "node");
circles.transition()
.duration(1000)
.attr("r", function(d) {
return d.r;
})
.each('end', function() {
display_text();
});
function display_text() {
let text = svg
.selectAll(".text")
.data(nodes, function(d) {
return d[columnForText];
});
text.enter().append("text")
.attr("class", "graphText")
.attr("x", function(d) {
return d.x;
})
.attr("y", function(d) {
return d.y - 20;
})
.attr("dy", ".2em")
.attr("fill", "white")
.attr("font-size", function(d) {
return d.r / 5;
})
.attr("text-anchor", "middle")
.text(function(d) {
console.log(d)
return d[columnForText].substring(0, d.r / 3);
});
text.enter().append("text")
.attr("class", "graphText")
.attr("x", function(d) {
return d.x;
})
.attr("y", function(d) {
return d.y - 20;
})
.attr("dy", "1.3em")
.style("text-anchor", "middle")
.text(function(d) {
return '$' + d[columnForRadius];
})
.attr("font-size", function(d) {
return d.r / 5;
})
.attr("fill", "white");
}
function hide_text() {
let text = svg.selectAll(".text").remove();
}
d3.select(self.frameElement)
.style("height", diameter + "px");
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js"></script>
<script type="text/javascript">
var dataset = [
{ "Name": "Olives", "Count": 4319, "Category": "d" },
{ "Name": "Tea", "Count": 4159, "Category": "d" },
{ "Name": "Boiled Potatoes", "Count": 2074, "Category": "a" },
{ "Name": "Milk", "Count": 1894, "Category": "a" },
{ "Name": "Chicken Salad", "Count": 1809, "Category": "a" },
{ "Name": "Lettuce Salad", "Count": 1566, "Category": "a" },
{ "Name": "Lobster Salad", "Count": 1511, "Category": "a" },
{ "Name": "Chocolate", "Count": 1489, "Category": "b" }
];
var width = 300, diameter = 300;
var columnForText = 'Name',
columnForColors = 'Category',
columnForRadius = "Count";
</script>
Here's my fiddle: http://jsfiddle.net/71s86zL7/
I created a compound bubble pie chart and specified the inner radius in the pie chart.
var arc = d3.svg.arc()
.innerRadius(radius)
.outerRadius(radius);
.attr("d", function(d) {
arc.innerRadius(d.r+5);
arc.outerRadius(d.r);
return arc(d);
})
please let me know if there's any alternative solution to this problem.
I have a sorta hacky solution for this. What I did was:
to use the d3.layout.pie to get the startAngles and endAngles for arcs and create the arcs on top of the circles.
Give the circles a stroke line creating an effect of a donut chart.
And then I just had to adjust the startAngles and the endAngles so that all the arcs start from the same position.
Here's the fiddle:
let colorCircles = {
'a': '#59bcf9',
'b': '#faabab',
'd': '#ffde85'
};
let tooltip = d3.select("body")
.append("div")
.attr("class", "tooltip-inner")
.style("position", "absolute")
.style("min-width", "12rem")
.style("visibility", "hidden")
.style("color", "#627386")
.style("padding", "15px")
.style("stroke", '#b8bfca')
.style("fill", "none")
.style("stroke-width", 1)
.style("background-color", "#fff")
.style("border-radius", "6px")
.style("text-align", "center")
.text("");
let bubble = d3.layout.pack()
.sort(null)
.size([width, diameter])
.padding(15)
.value(function(d) {
return d[columnForRadius];
});
var pie = d3.layout.pie()
.sort(null)
.value(function(d) {
return d.Count;
});
var arc = d3.svg.arc()
let svg = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", diameter)
.attr("class", "bubble");
let nodes = bubble.nodes({
children: dataset
}).filter(function(d) {
return !d.children;
});
let g = svg.append('g')
let circles = g.selectAll("circle")
.data(nodes)
.enter()
.append("circle")
.attr("r", function(d) {
return d.r;
})
.attr("cx", function(d) {
return d.x;
})
.attr("cy", function(d) {
return d.y - 20;
})
.style("fill", function(d) {
return colorCircles[d[columnForColors]]
})
.attr("class", "node")
.on("mouseover", function(d) {
tooltip.style("visibility", "visible");
tooltip.html('<p>' + d[columnForColors] + ": " + d[columnForText] + "</p><div class='font-bold displayInlineBlock'> $" + d[columnForRadius] + '</div>');
})
.on("mousemove", function() {
return tooltip.style("top", (d3.event.offsetY - 10) + "px").style("left", (d3.event.offsetX + 10) + "px");
})
.on("mouseout", function() {
return tooltip.style("visibility", "hidden");
});
arcs = g.selectAll(".arc")
.data(pie(dataset))
.enter().append("g")
.attr("class", "arc");
arcs.append("path")
.attr('transform', function(d) {
return 'translate(' + d['data']['x'] + ',' + (d['data']['y'] - 20) + ')';
})
.attr("d", function(d) {
return arc({
startAngle: 0,
endAngle: d.startAngle - d.endAngle,
innerRadius: d['data']['r'] - 2,
outerRadius: d['data']['r'] + 2,
})
}).on("mouseover", function(d) {
tooltip.style("visibility", "visible");
tooltip.html('<p>' + d['data'][columnForColors] + ": " + d['data'][columnForText] + "</p><div class='font-bold displayInlineBlock'> $" + d['data'][columnForRadius] + '</div>');
})
.on("mousemove", function() {
return tooltip.style("top", (d3.event.offsetY - 10) + "px").style("left", (d3.event.offsetX + 10) + "px");
})
.on("mouseout", function() {
return tooltip.style("visibility", "hidden");
});
circles.transition()
.duration(1000)
.attr("r", function(d) {
return d.r;
})
.each('end', function() {
display_text();
});
function display_text() {
let text = svg
.selectAll(".text")
.data(nodes, function(d) {
return d[columnForText];
});
text.enter().append("text")
.attr("class", "graphText")
.attr("x", function(d) {
return d.x;
})
.attr("y", function(d) {
return d.y - 20;
})
.attr("dy", ".2em")
.attr("fill", "white")
.attr("font-size", function(d) {
return d.r / 3;
})
.attr("text-anchor", "middle")
.text(function(d) {
return d[columnForText].substring(0, d.r / 3);
});
text.enter().append("text")
.attr("class", "graphText")
.attr("x", function(d) {
return d.x;
})
.attr("y", function(d) {
return d.y - 20;
})
.attr("dy", "1.3em")
.style("text-anchor", "middle")
.text(function(d) {
return '$' + d[columnForRadius];
})
.attr("font-size", function(d) {
return d.r / 5;
})
.attr("fill", "white");
}
function hide_text() {
let text = svg.selectAll(".text").remove();
}
d3.select(self.frameElement)
.style("height", diameter + "px");
path {
fill: orange;
stroke-width: 1px;
stroke: crimson;
}
path:hover {
fill: yellow;
}
circle {
fill: white;
stroke: slategray;
stroke-width: 4px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.3.13/d3.min.js"></script>
<script type="text/javascript">
var dataset = [{
"Name": "Olives",
"Count": 4319,
"Category": "d"
},
{
"Name": "Tea",
"Count": 4159,
"Category": "d"
},
{
"Name": "Boiled Potatoes",
"Count": 2074,
"Category": "a"
},
{
"Name": "Milk",
"Count": 1894,
"Category": "a"
},
{
"Name": "Chicken Salad",
"Count": 1809,
"Category": "a"
},
{
"Name": "Lettuce Salad",
"Count": 1566,
"Category": "a"
},
{
"Name": "Lobster Salad",
"Count": 1511,
"Category": "a"
},
{
"Name": "Chocolate",
"Count": 1489,
"Category": "b"
}
];
var width = 300,
diameter = 300;
var columnForText = 'Name',
columnForColors = 'Category',
columnForRadius = "Count";
</script>