I'm trying to display a donut chart within a tooltip. I thought it'll be simply just adding the function name or creating the chart within .html() but that isn't the case sadly. Can anyone tell me where i'm going wrong?
Here's my code:
tooltip.select('.label').html(donutChart());
function donutChart(){
var dataset = {
hddrives: [20301672448, 9408258048, 2147483648, 21474836480, 35622912,32212254720],
};
var width = 460,
height = 300,
radius = Math.min(width, height) / 2;
var color = d3.scale.ordinal()
.range(["#2DA7E2"]);
var pie = d3.layout.pie()
.sort(null);
var arc = d3.svg.arc()
.innerRadius(radius - 100)
.outerRadius(radius - 70);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
var path = svg.selectAll("path")
.data(pie(dataset.hddrives))
.enter().append("path")
.attr("class", "arc")
.attr("fill", function(d, i) { return color(i); })
.attr("d", arc);
svg.append("text")
.attr("dy", ".35em")
.style("text-anchor", "middle")
.attr("class", "inside")
.text(function(d) { return 'Test'; });
}
Your function donutChart appends the <svg> to the body, not inside the tooltip.
A solution can be writing this in your .html():
.html("<h1>My Donut Chart</h1><br><svg class='myDonut'></svg>")
And then call your donutChart after that line, remembering to change your var svg:
var svg = d3.select(".myDonut")
Take care for not repeating the same variable names, even if they are inside a function (separate scope)... it can cause unnecessary confusion.
Related
I am facing issue for getting more than 30 legends and that legends could not be shown in vertical way nor horizontal way.
I would like to add scrollbar to only legend box so that all legends would be visible with scroll or is there any way to add legends side by side like 3 in a row something like that
I tried adding overflow property but could not work.
Below is my code
var data =[];
for(var p = 0 ;p <unique.length;p++)
{
data.push({
legendLabel:unique[p],
magnitude:uniquecount[p]
});
}
var canvasWidth = this.getWidth(), //width
canvasHeight = this.getHeight(), //height
outerRadius = 60, //radius
color = d3.scale.category20(); //builtin range of colors
var vis = d3.select("#"+this.htmlObject)
.append("svg:svg") //create the SVG element inside the <body>
.data([data]) //associate our data with the document
.attr("width", canvasWidth) //set the width of the canvas
.attr("height", canvasHeight) //set the height of the canvas
.append("svg:g") //make a group to hold our pie chart
.attr("transform", "translate(" + 1.5*outerRadius + "," + 1.5*outerRadius + ")") // relocate center of pie to 'outerRadius,outerRadius'
.attr('transform', 'translate(' + (canvasWidth/2 - 50) + ',' + canvasHeight/2 +')');
vis.append("text")
.attr("x",50)
.attr("y", -110)
.attr("text-anchor", "middle")
.style("font-size", "14px")
.text("Response Code vs Count(Last 20 Mins)");
if(unique.length === 0)
{
vis.append("text")
.attr("x",50)
.attr("y", 0)
.attr("text-anchor", "middle")
.style("font-size", "12px")
.text("No Failure Transactions");
}
// This will create <path> elements for us using arc data...
var arc = d3.svg.arc()
.outerRadius(outerRadius);
var pie = d3.layout.pie() //this will create arc data for us given a list of values
.value(function(d) { return d.magnitude; }); // Binding each value to the pie
// Select all <g> elements with class slice (there aren't any yet)
var arcs = vis.selectAll("g.slice")
// Associate the generated pie data (an array of arcs, each having startAngle,
// endAngle and value properties)
.data(pie)
// This will create <g> elements for every "extra" data element that should be associated
// with a selection. The result is creating a <g> for every object in the data array
.enter()
// Create a group to hold each slice (we will have a <path> and a <text>
// element associated with each slice)
.append("svg:g")
.attr("class", "slice"); //allow us to style things in the slices (like text)
arcs.append("svg:path")
//set the color for each slice to be chosen from the color function defined above
.attr("fill", function(d, i) { return color(i); } )
.attr("data-legend",function(d) { return d.data.legendLabel +"->" + d.data.magnitude})
//this creates the actual SVG path using the associated data (pie) with the arc drawing function
.attr("d", arc);
// Add a magnitude value to the larger arcs, translated to the arc centroid and rotated.
arcs.filter(function(d) { return d.endAngle - d.startAngle > .2; }).append("svg:text")
.attr("dy", ".35em")
.attr("text-anchor", "middle")
//.attr("transform", function(d) { return "translate(" + arc.centroid(d) + ")rotate(" + angle(d) + ")"; })
.attr("transform", function(d) { //set the label's origin to the center of the arc
//we have to make sure to set these before calling arc.centroid
d.outerRadius = outerRadius; // Set Outer Coordinate
d.innerRadius = outerRadius/2; // Set Inner Coordinate
return "translate(" + arc.centroid(d) + ")rotate(" + angle(d) + ")";
})
.style("fill", "White")
.style("font", "bold 12px Arial")
.text(function(d) { return d.data.magnitude; });
legend = vis.append("g")
.attr("class","legend")
.attr("overflow-y","auto")
.attr("transform","translate(70,-50)")
.style("font-size","13px")
.call(d3.legend);
// Computes the angle of an arc, converting from radians to degrees.
function angle(d) {
var a = 180;
return a > 90 ? a - 180 : a;
}
}
else
{
var canvasWidth = this.getWidth(), //width
canvasHeight = this.getHeight(), //height
outerRadius = 75, //radius
color = d3.scale.category20(); //builtin range of colors
var viN = d3.select("#"+this.htmlObject)
.append("svg:svg") //create the SVG element inside the <body>
.attr("width", canvasWidth) //set the width of the canvas
.attr("height", canvasHeight) //set the height of the canvas
.append("svg:g"); //make a group to hold our pie chart
viN.append("text")
.attr("x",200)
.attr("y", 30)
.attr("text-anchor", "middle")
.style("font-size", "14px")
.text("Response Code vs Count(Last 20 Mins)");
viN.append("text")
.attr("x",200)
.attr("y", 100)
.attr("text-anchor", "middle")
.style("font-size", "12px")
.text("No data Found");
}
i have added the D3 script to my web application which is developed by angularjs.
the D3 graph is drawn but multiple graphs are appear every time i access to the tabs.
Below is the script i used.
<script type="text/javascript">
data = [{"value":200},
{"value":100}];
var w = 300,
h = 300,
r = 100,
color = d3.scale.category20c();
/*var canvas = d3.select("body").append("svg:svg").data([data])
.attr("width", w)
.attr("height", h)
.append("svg:g")
.attr("transform", "translate(" + r + "," + r + ")")*/
var canvas = d3.select("body svg:svg");
if(!svg){
canvas = d3.select("body")
.append("svg:svg").data([data])
.attr("width", w)
.attr("height", h)
.append("svg:g")
.attr("transform", "translate(" + r + "," + r + ")")
}
var arc = d3.svg.arc()
.outerRadius(r);
var pie = d3.layout.pie()
.value(function(d) { return d.value; });
var arcs = canvas.selectAll("g.slice")
.data(pie)
.enter()
.append("svg:g")
.attr("class", "slice");
arcs.append("svg:path")
.attr("fill", function(d, i) { return color(i); } )
.attr("d", arc);
arcs.append("svg:text")
.attr("transform", function(d) {
d.innerRadius = 0;
d.outerRadius = r;
return "translate(" + arc.centroid(d) + ")";
})
.attr("text-anchor", "middle")
.text(function(d, i) { return data[i].value; });
</script>
i added this script to the view that i wanted to show the graph.but after accessing to the specific tab the graph is show in every tab of my application.
As above image the grpagh is generated every time access to the tab/view.
can anyone help me this.
Thanks
Why don't you want to use unique element with id for your chart?
var canvas = d3.select("body svg:svg");
if(!svg){
canvas = d3.select("body")
Try to change it to something like
var canvas = d3.select("#yourId svg:svg");
if(!svg){
canvas = d3.select("#yourId")
Also add <div id='yourId'></div> tag to a tab, where your chart should be
Try removing svg before rendering another svg
d3.select("svg").remove();
What I'm trying to do is make two charts display in the same field, one to show the time spent working vs. the time spent idling, and the other chart to show whether the machine is currently working or idling.
I want the chart that shows the machine idling to be smaller than the first and fit inside it. I've been able to make both charts but I am unable to combine them in the way that I want them to.
[what I have right now]
[what I'd like to do]
Here is my code:
<!DOCTYPE html>
<html lang="en">
<div id="chart-center-jc1" align="center"></div>
<!--this line control location of the SVG chart-->
<script src="d3/d3.v3.min.js"></script>
<script>
var radius = 80,
padding = 10;
var radius2 = 25,
padding = 10;
var color = d3.scale.ordinal()
.range([ "#fc0303", "#21d525", "#d0cece", "#a05d56", "#d0743c", "#ff8c00"]);
var arc = d3.svg.arc()
.outerRadius(radius)
.innerRadius(radius - 30);
var arc2 = d3.svg.arc()
.outerRadius(radius2)
.innerRadius(radius2 - 25);
var pie = d3.layout.pie()
.sort(null)
.value(function(d) { return d.population; });
var pie2 = d3.layout.pie()
.sort(null)
.value(function(d) { return d.population; });
d3.csv("M1 Summary.csv", function(error, data) {
if (error) throw error;
color.domain(d3.keys(data[0]).filter(function(key) { return key !=="Machine"; }));
data.forEach(function(d) {
d.ages = color.domain().map(function(name) {
return {name: name, population: +d[name]};
});
});
var legend = d3.select("#chart-center-jc1").append("svg")
.attr("class", "legend")
.attr("width", radius * 2)
.attr("height", radius * 2)
.selectAll("g")
.data(color.domain().slice().reverse())
.enter().append("g")
.attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; });
legend.append("rect")
.attr("width", 18)
.attr("height", 18)
.style("fill", color);
legend.append("text")
.attr("x", 24)
.attr("y", 9)
.attr("dy", ".35em")
.text(function(d) { return d; });
var svg = d3.select("#chart-center-jc1").selectAll(".pie")
.data(data)
.enter().append("svg")
.attr("class", "pie2")
.attr("width", radius * 2)
.attr("height", radius * 3)
.append("g")
.attr("transform", "translate(" + radius + "," + radius + ")");
svg.selectAll(".arc")
.data(function(d) { return pie(d.ages); })
.enter().append("path")
.attr("class", "arc")
.attr("d", arc)
.style("fill", function(d) { return color(d.data.name); });
svg.selectAll(".arc2")
.data(function(d) { return pie2(d.ages); })
.enter().append("path")
.attr("class", "arc2")
.attr("d", arc2)
.style("fill", function(d) { return color(d.data.name); });
});
The key is to append one svg onto another:
var svg = d3.select("#chart-center-jc1").append("svg")
.attr("width", radius * 2)
.attr("height", radius * 3)
.attr("class","outerPie")
.append("g")
.attr("transform", "translate(" + radius + "," + radius + ")");
var svg2 = d3.select(".outerPie").append("svg")
.attr("width", radius * 2)
.attr("height", radius * 3)
.attr("class","innerPie")
.append("g")
.attr("transform", "translate(" + radius + "," + radius + ")");
Note that both svgs have the same height, width, and translate. This is because they are on top of one another, and you want to position the second in the center of the first.
See fiddle for complete solution.
Just started using d3.js and javascript. I have this weird chart requirement. Want to create the chart exactly like pie chart but, in square shaped. Just like below.
So, I thought, may be I create the pie chart and add the square between the pie chart and erase the part outside square. But, it is not working out yet.
Secondly, I thought, I can do this with CSS. I did this. But, I am not happy with this solution. It is too hacky. Can someone help me with good solution.
This is my jsfiddle link.
//// Done this to create the square.
var svgContainer = d3.select("#square").append("svg")
.attr("width", 200)
.attr("height", 200);
var rectangle = svgContainer.append("rect")
.attr("x", 0)
.attr("y", 0)
.attr("width", 200)
.attr("fill", '#ec4c4a')
.attr("height", 200);
// Done this to create the pie chart. Found this example some where.
var element_id = 'pie'
var elementSelector = '#pie';
svgWidth = 390;
svgHeight = 320;
svgInnerRadius = 0;
svgOuterRadius = 145;
heightOffset = 0;
scoreFontSize = '49px';
$(elementSelector).replaceWith('<svg id="'+ element_id +'" class="scoreBar" width="'+ svgWidth +'" height="'+ (svgHeight - heightOffset) +'"></svg>');
$(elementSelector).css({'width': svgWidth + 'px', 'height': (svgHeight-heightOffset) + 'px'});
var anglePercentage = d3.scale.linear().domain([0, 100]).range([0, 2 * Math.PI]);
var fullAnglePercentage = 100;
var color = d3.scale.ordinal().range(["#ACACAC", "#EAEAEA", "#123123", "#DDEEAA", "#BACBAC"]);
data = [[50, 90, 1],
[50, 30, 2],
[30, 10, 3],
[10, -1, 4],
[-1, -10, 5]]
var vis = d3.select(elementSelector);
var arc = d3.svg.arc()
.innerRadius(svgInnerRadius)
.outerRadius(svgOuterRadius)
.startAngle(function(d){return anglePercentage(d[0]);})
.endAngle(function(d){return anglePercentage(d[1]);});
vis.selectAll("path")
.data(data)
.enter()
.append("path")
.attr("d", arc)
.style("fill", function(d){return color(d[2]);})
.attr("transform", "translate(" + svgWidth / 2 + ", " + svgHeight / 2 + ")");
Thanks in advance.
You can achieve this using clip path. What is a clip path?
To SVG add defs of clippath
var svg1 = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
//making a clip square as per your requirement.
svg1.append("defs").append("svg:clipPath")
.attr("id", "clip")
.append("svg:rect")
.attr("id", "clip-rect")
.attr("x", -120)
.attr("y", -100)
.attr("width", radius)
.attr("height", radius);
Make your normal d3 pie chart like:
var g = svg.selectAll(".arc")
.data(pie(data))
.enter().append("g")
.attr("class", "arc");
g.append("path")
.attr("d", arc)
.style("fill", function (d) {
return color(d.data.age);
});
To the main group add the clip like this:
var svg = svg1.append("g").attr("clip-path", "url(#clip)")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
Full working code here.
http://tributary.io/inlet/10932495
I can't seem to figure out why my text labels are not showing up on my chart. Help or suggestions? Link above shows my pie chart and my code as well as my csv data.
var arvadaData = tributary.arvadaPayments
var sumPayments = d3.sum(arvadaData, function(d) {return +d.payments;});
var svg = d3.select("svg");
var width = 527,
height = 562,
radius = Math.min(width, height) / 2;
var outerRadius = width/2;
var colorScale = d3.scale.category20(); //built in range of 20 colors
var arc = d3.svg.arc() //creates <path> elements using arc data
.outerRadius(width / 2)
.innerRadius(100);
var pie = d3.layout.pie()
.sort(null)
.value(function(d){ return +d.payments });
var g = svg.selectAll("g.arc")
.data(pie(arvadaData))
.enter()
.append("g")
.attr("class", "arc")
.attr("transform", "translate(" + width/2 + "," + height/2 + ")");
g.append("path")
.attr("fill", function(d, i){return colorScale(i);})
.attr("d", arc);
g.append("text")
.attr("transform", function(d){ return "translate(" + arc.centroid(d) +")"; })
.attr("text-anchor", "middle")
.text(function(d){ return d[i].specialty; });
The text elements are added and positioned correctly, but their content isn't set correctly. You're passing in the data coming from the pie layout -- the original data is available under the .data member in this case. That is, the expression to set the text should be
.text(function(d){ return d.data.specialty; });
Complete demo here.