none
SharePoint and D3.js for charting RRS feed

  • Question

  • Anyone have any true example using a list in sharepoint and d3.js code to make a chart?
    Majority of stuff online seems to be very fatigue. Anyone have step by step instructions

    https://d3js.org/

    Tuesday, April 11, 2017 5:59 PM

All replies

  • Hi,

    The following example about using d3.js and SharePoint List build a Pie Chart for your reference:

    1. Create a custom list in SharePoint, and add a Number column in list. In my case, the list name "CustomList21" and new column name "Value".

    2. Add some data into custom List.

    3. Add the following code into a script editor web part in the web part page(I add the code in list view page).

    <script src="//code.jquery.com/jquery-3.2.1.min.js" type="text/javascript"></script>
    <script type="text/javascript" src="http://mbostock.github.com/d3/d3.js?2.1.3"></script> 
    <script type="text/javascript" src="http://mbostock.github.com/d3/d3.geom.js?2.1.3"></script> 
    <script type="text/javascript" src="http://mbostock.github.com/d3/d3.layout.js?2.1.3"></script> 
    <script type="text/javascript">
    $(function () { 
    	var chartData=getListData("CustomList21");
    	var data=[];
    	for(var i=0;i<chartData.length;i++){
    		data.push({"label":chartData[i].Title,"value":chartData[i].Value});
    	}
    	initChart(data);
    });
    function initChart(chartData){
    	var w = 300,                        //width
    	h = 300,                            //height
    	r = 100,                            //radius
    	color = d3.scale.category20c();     //builtin range of colors
    
    	data = chartData;
    	
    	var vis = d3.select("#PieChart")
    		.append("svg:svg")              //create the SVG element inside the <div id="PieChart"></div>
    		.data([data])                   //associate our data with the document
    			.attr("width", w)           //set the width and height of our visualization (these will be attributes of the <svg> tag
    			.attr("height", h)
    		.append("svg:g")                //make a group to hold our pie chart
    			.attr("transform", "translate(" + r + "," + r + ")")    //move the center of the pie chart from 0, 0 to radius, radius
    
    	var arc = d3.svg.arc()              //this will create <path> elements for us using arc data
    		.outerRadius(r);
    
    	var pie = d3.layout.pie()           //this will create arc data for us given a list of values
    		.value(function(d) { return d.value; });    //we must tell it out to access the value of each element in our data array
    
    	var arcs = vis.selectAll("g.slice")     //this selects all <g> elements with class slice (there aren't any yet)
    		.data(pie)                          //associate the generated pie data (an array of arcs, each having startAngle, endAngle and value properties) 
    		.enter()                            //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
    			.append("svg:g")                //create a group to hold each slice (we will have a <path> and a <text> element associated with each slice)
    				.attr("class", "slice");    //allow us to style things in the slices (like text)
    
    		arcs.append("svg:path")
    				.attr("fill", function(d, i) { return color(i); } ) //set the color for each slice to be chosen from the color function defined above
    				.attr("d", arc);                                    //this creates the actual SVG path using the associated data (pie) with the arc drawing function
    
    		arcs.append("svg:text")                                     //add a label to each slice
    				.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.innerRadius = 0;
    				d.outerRadius = r;
    				return "translate(" + arc.centroid(d) + ")";        //this gives us a pair of coordinates like [50, 50]
    			})
    			.attr("text-anchor", "middle")                          //center the text on it's origin
    			.text(function(d, i) { return data[i].label; });        //get the label from our original data array       
    
    }	
    function getListData(listName){
    	var results;	
    	var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('"+listName+"')/items?$select=Title,Value";
    	$.ajax({
    		url: requestUri,
    		type: "GET",
    		async:false,
    		headers: { "ACCEPT": "application/json;odata=verbose" },
    		success: function (data) {			
    			results=data.d.results;
    		},
    		error: function () {
    			//alert("Failed to get details");                
    		}
    	});
    	return results;
    }
    </script>
    <div id="PieChart"></div>

    If you want to create another type chart, I suggest you lean the knowledge of the d3.js from here:

    https://github.com/d3/d3/wiki/Gallery

    Best Regards,

    Dennis


    Please remember to mark the replies as answers if they help.
    If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com

    Wednesday, April 12, 2017 2:47 AM
    Moderator
  • This looks promising and I appreciate the detail but these do not seem to exist to be able to replicate what you described.

    <script type="text/javascript" src="http://mbostock.github.com/d3/d3.geom.js?2.1.3"></script>
    <script type="text/javascript" src="http://mbostock.github.com/d3/d3.layout.js?2.1.3"></script>

    Wednesday, April 12, 2017 6:09 PM
  • Hi,

    I modify the code using the new D3.JS API to achieve it. Check the code below:

    <style>
    .arc text {
      font: 15px sans-serif;
      text-anchor: middle;
    }
    
    .arc path {
      stroke: #fff;
    }
    </style>
    
    <svg width="300" height="300"></svg>
    <script src="//code.jquery.com/jquery-3.2.1.min.js" type="text/javascript"></script>
    <script src="//d3js.org/d3.v4.min.js" type="text/javascript"></script>
    <script type="text/javascript">
    $(function () { 
    	var chartData=getListData("CustomList21");
    	initChart(chartData);
    });
    function initChart(chartData){
    	var svg = d3.select("svg"),
        width = +svg.attr("width"),
        height = +svg.attr("height"),
        radius = Math.min(width, height) / 2,
        g = svg.append("g").attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
    
    	var color = d3.scaleOrdinal(["#ffabc5", "#8affa6", "#7b68ff"]);
    	
    	var pie = d3.pie()
    	    .sort(null)
    	    .value(function(d) { return d.Value; });
    	
    	var path = d3.arc()
    	    .outerRadius(radius - 10)
    	    .innerRadius(0);
    	
    	var label = d3.arc()
    	    .outerRadius(radius - 40)
    	    .innerRadius(radius - 40);
    	    
    	var arc = g.selectAll(".arc")
    	    .data(pie(chartData))
    	    .enter().append("g")
    	      .attr("class", "arc");
    
     	 arc.append("path")
          .attr("d", path)
          .attr("fill", function(d) { return color(d.data.Title); });
    
      arc.append("text")
          .attr("transform", function(d) { return "translate(" + label.centroid(d) + ")"; })
          .attr("dy", "0.35em")
          .text(function(d) {return d.data.Title;});
        
       
    }	
    function getListData(listName){
    	var results;	
    	var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('"+listName+"')/items?$select=Title,Value";
    	$.ajax({
    		url: requestUri,
    		type: "GET",
    		async:false,
    		headers: { "ACCEPT": "application/json;odata=verbose" },
    		success: function (data) {			
    			results=data.d.results;
    		},
    		error: function () {
    			//alert("Failed to get details");                
    		}
    	});
    	return results;
    }
    </script>
    

    Best Regards,

    Dennis


    Please remember to mark the replies as answers if they help.
    If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com

    Thursday, April 13, 2017 3:07 AM
    Moderator
  • Dear,

    I need to change the columns in your code how can i do that ? as i tried but its not showing the graph :(

    if i say i want to replace the title column with my some other column and same for value column how can i do that? please help


    Thursday, April 27, 2017 9:50 AM
  • Hi,

    Please provide your column name for further research.

    Best Regards,

    Dennis


    Please remember to mark the replies as answers if they help.
    If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com

    Thursday, April 27, 2017 9:56 AM
    Moderator
  • Hi,

    for Title column i want "ProjectName" and for value i need "FinancialCompletion"

    Regards,

    Zubair

    Thursday, April 27, 2017 10:08 AM
  • Hi,

    Please modify the code like this:

    <script type="text/javascript">
    $(function () { 
    	var chartData=getListData("CustomList21");
    	initChart(chartData);
    });
    function initChart(chartData){
    	var svg = d3.select("svg"),
        width = +svg.attr("width"),
        height = +svg.attr("height"),
        radius = Math.min(width, height) / 2,
        g = svg.append("g").attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
    
    	var color = d3.scaleOrdinal(["#ffabc5", "#8affa6", "#7b68ff"]);
    	
    	var pie = d3.pie()
    	    .sort(null)
    	    .value(function(d) { return d.FinancialCompletion; });
    	
    	var path = d3.arc()
    	    .outerRadius(radius - 10)
    	    .innerRadius(0);
    	
    	var label = d3.arc()
    	    .outerRadius(radius - 40)
    	    .innerRadius(radius - 40);
    	    
    	var arc = g.selectAll(".arc")
    	    .data(pie(chartData))
    	    .enter().append("g")
    	      .attr("class", "arc");
    
     	 arc.append("path")
          .attr("d", path)
          .attr("fill", function(d) { return color(d.data.ProjectName); });
    
      arc.append("text")
          .attr("transform", function(d) { return "translate(" + label.centroid(d) + ")"; })
          .attr("dy", "0.35em")
          .text(function(d) {return d.data.ProjectName;});
        
       
    }	
    function getListData(listName){
    	var results;	
    	var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('"+listName+"')/items?$select=ProjectName,FinancialCompletion";
    	$.ajax({
    		url: requestUri,
    		type: "GET",
    		async:false,
    		headers: { "ACCEPT": "application/json;odata=verbose" },
    		success: function (data) {			
    			results=data.d.results;
    		},
    		error: function () {
    			//alert("Failed to get details");                
    		}
    	});
    	return results;
    }
    </script>

    Best Regards,

    Dennis


    Please remember to mark the replies as answers if they help.
    If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com

    Thursday, April 27, 2017 10:13 AM
    Moderator
  • I tried your code and change the list name with my list name but its not displaying the graph :(
    Thursday, April 27, 2017 10:48 AM
  • Hi,

    Please check whether the "ProjectName" and the "FinancialCompletion" is the column internal name or not.

    Best Regards,

    Dennis


    Please remember to mark the replies as answers if they help.
    If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com

    Thursday, April 27, 2017 11:01 AM
    Moderator
  • its internal names :(
    Thursday, April 27, 2017 11:10 AM
  • One thing i want to add that i have many columns in the list. These columns are in different positions like one is in the start of the list and the other is in last ( kind of indexing) any issue with this?

    Thursday, April 27, 2017 11:13 AM
  • Hi,

    Please provide the columns type or share your list structure if possible.

    Or open your browser and check whether it works using the REST URL below:

    http://yoursiteurl/_api/web/lists/getbytitle('yourlistname')/items?$select=ProjectName,FinancialCompletion

    Best Regards,

    Dennis


    Please remember to mark the replies as answers if they help.
    If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com

    Thursday, April 27, 2017 11:29 AM
    Moderator
  • Project Name is Single line text (string)

    Financial Completion is number

    Thursday, April 27, 2017 11:42 AM
  • Hi,

    It works in my test environment. Please try to create new custom list to test it.

    Or check whether you can access //d3js.org/d3.v4.min.js in your sever.

    Or provide the screenshots for further research.

    Best Regards,

    Dennis 


    Please remember to mark the replies as answers if they help.
    If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com

    Thursday, April 27, 2017 12:11 PM
    Moderator
  • Can you please post me the code of above graph?

    Thursday, April 27, 2017 2:32 PM
  • i tried but did not work for me :(

    i have created a new custom list but unable to draw a graph. also  //d3js.org/d3.v4.min.js its working in my server

    Thursday, April 27, 2017 4:56 PM
  • Hi,

    The code as below:

    <style>
    .arc text {
      font: 15px sans-serif;
      text-anchor: middle;
    }
    
    .arc path {
      stroke: #fff;
    }
    </style>
    
    <svg width="300" height="300"></svg>
    <script src="//code.jquery.com/jquery-3.2.1.min.js" type="text/javascript"></script>
    <script src="//d3js.org/d3.v4.min.js" type="text/javascript"></script>
    <script type="text/javascript">
    $(function () { 
    	var chartData=getListData("CustomList5");
    	initChart(chartData);
    });
    function initChart(chartData){
    	var svg = d3.select("svg"),
        width = +svg.attr("width"),
        height = +svg.attr("height"),
        radius = Math.min(width, height) / 2,
        g = svg.append("g").attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
    
    	var color = d3.scaleOrdinal(["#ffabc5", "#8affa6", "#7b68ff"]);
    	
    	var pie = d3.pie()
    	    .sort(null)
    	    .value(function(d) { return d.FinancialCompletion; });
    	
    	var path = d3.arc()
    	    .outerRadius(radius - 10)
    	    .innerRadius(0);
    	
    	var label = d3.arc()
    	    .outerRadius(radius - 40)
    	    .innerRadius(radius - 40);
    	    
    	var arc = g.selectAll(".arc")
    	    .data(pie(chartData))
    	    .enter().append("g")
    	      .attr("class", "arc");
    
     	 arc.append("path")
          .attr("d", path)
          .attr("fill", function(d) { return color(d.data.ProjectName); });
    
      arc.append("text")
          .attr("transform", function(d) { return "translate(" + label.centroid(d) + ")"; })
          .attr("dy", "0.35em")
          .text(function(d) {return d.data.ProjectName;});
        
       
    }	
    function getListData(listName){
    	var results;	
    	var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('"+listName+"')/items?$select=ProjectName,FinancialCompletion";
    	$.ajax({
    		url: requestUri,
    		type: "GET",
    		async:false,
    		headers: { "ACCEPT": "application/json;odata=verbose" },
    		success: function (data) {			
    			results=data.d.results;
    		},
    		error: function () {
    			//alert("Failed to get details");                
    		}
    	});
    	return results;
    }
    </script>

    If you activate the Minimal Download Strategy(MDS) feature, please deactivate it and then test the code if it works.

    https://msdn.microsoft.com/en-us/library/office/dn456544.aspx?f=255&MSPPError=-2147217396

    Best Regards,

    Dennis


    Please remember to mark the replies as answers if they help.
    If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com


    Friday, April 28, 2017 1:10 AM
    Moderator
  • Can i show the tool tip type thing on mouse hover on the graph division by showing the values of financial completion?
    Friday, April 28, 2017 5:09 AM