This time is to draw a pie chart, and this time using D3 to draw the last piece of the chart, you can learn from other places in-depth D3 to draw the chart, you can also directly see the D3 API to learn, this time to draw the pie chart data with the previous unload array is not the same, this time is the use of D3 csv (URL) function read a data.csv file, in this declaration, if the Web page editor is not using the server to open the Web page, it will not be able to read the CSV file error, I use the hbuilder here, a good editor.
1.data.csv files, written as key-value pairs
Education,population College and above, 11964 High school and secondary school, 18799 Middle School, 51966 Primary School, 35876 illiterate population, 5466
2.html code, still as simple as usual
<!DOCTYPE HTML><HTML> <Head> <MetaCharSet= "UTF-8"> <title></title> </Head> <Body> <DivID= "Container"></Div> </Body> <Scripttype= "Text/javascript"src= "Js/d3.js" ></Script> <Scripttype= "Text/javascript"src= "Js/pinzhuangtu.js" ></Script></HTML>
3.js Code
D3.csv ("Data.csv", type,function(data) {width= 400, Height= 400; varSVG = D3.select ("#container"). Append ("SVG"). attr ({"Width": Width,"Height": Height}) varg = Svg.append ("G"). attr ("Transform", "translate (200, 200)") varArc_generator =D3.svg.arc (). Innerradius (100)//set Inner radius. Outerradius (200)//set the outer radius varAngle_data =D3.layout.pie (). Value (function(d) {returnd.population;}) Console.log (Angle_data (data)); varcolor =D3.scale.category10 (); G.selectall ("Path"). Data (Angle_data (data)). Enter (). Append ("Path"). attr ("D", Arc_generator). Style ("Fill",function(d,i) {returnColor (i)})//fill different sectors with different colorsG.selectall ("Text")//add the corresponding text to each fan. Data (Angle_data (data)). Enter (). Append ("Text"). Text (function(d) {returnd.data.education}). attr ("Transform",function(d) {return"Translate (" +arc_generator.centroid (d) + ")"})//adjust to the corresponding position of each text. attr ("Text-anchor", "Middle")//is text centered});functionType (d) {d.population=+d.population; returnD;}
4. Page Run effect
Draw a chart with D3 (7)--Pie chart