简体   繁体   中英

how to add legend in pie chart

I use php codeigniter and I create pie chart using javascript. and database data pass using json encode. My problem is how I use legend. for pie chart and title.

javascript

        var pieData = [
            {
                value: sales_data[i].ans,
                color:"#FF0000"

            },
            {
                value : sales_data[i].noans,
                color : "#006400"
            },
            {
                value : sales_data[i].reans,
                color : "#191970"
            }
            ,
            {
                value : sales_data[i].noreans,
                color : "#FFEA88"
            }
        ];
        // get pie chart canvas
        var countries=document.getElementById("countries").getContext("2d");                   
        // draw pie chart
        new Chart(countries).Pie(pieData, pieOptions);

                    }
        }
        });

Give this a shot -

 legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% 
for (var i=0; i<segments.length; i++){%><li><span style=\"background-color:
<%=segments[i].fillColor%>\"></span><%if(segments[i].label){%>
<%=segments[i].label%><%}%></li><%}%></ul>"

Include this as part of your pieOptions.

Refer this documentation of chart.js for more details on how to use chart.js. For legends there dosent seem to be a simple way but you have an option to give label to each segment in your piechart which will act as your legend.

var myPieChart = new Chart(ctx[0]).Pie(data,options);
var data = [
{
    value: 300,
    color:"#F7464A",
    highlight: "#FF5A5E",
    label: "Red",
    labelColor : 'white',
},
{
    value: 50,
    color: "#46BFBD",
    highlight: "#5AD3D1",
    label: "Green",
    labelColor : 'white',
},
{
    value: 100,
    color: "#FDB45C",
    highlight: "#FFC870",
    label: "Yellow",
    labelColor : 'white',
}
   ]

In this the label acts as your map legend and it looks like the example fiddle piechart using chart.js

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM