mattosaurus / ChartJSCore

Implementation of Chart.js for use with .NET Core.
GNU General Public License v3.0
116 stars 34 forks source link

PluginDynamic and dataLabels #85

Open asafgo opened 2 years ago

asafgo commented 2 years ago

Hi, Following https://github.com/mattosaurus/ChartJSCore/issues/44 percentage labels are not shown on Pie chart.

public class DataLabels
    {
        [JsonConverter(typeof(PlainJsonStringConverter))]
        public string Formatter { get; set; }

        public ChartColor Color { get; set; }
    }
private static Chart GeneratePieChart()
        {
            Chart chart = new Chart();
            chart.Type = Enums.ChartType.Pie;

            ChartJSCore.Models.Data data = new();
            data.Labels = new List<string>() { "Red", "Blue", "Yellow" };

            PieDataset dataset = new PieDataset()
            {
                Label = "My dataset",
                BackgroundColor = new List<ChartColor>() {
                    ChartColor.FromHexString("#FF6384"),
                    ChartColor.FromHexString("#36A2EB"),
                    ChartColor.FromHexString("#FFCE56")
                },
                HoverBackgroundColor = new List<ChartColor>() {
                    ChartColor.FromHexString("#FF6384"),
                    ChartColor.FromHexString("#36A2EB"),
                    ChartColor.FromHexString("#FFCE56")
                },
                Data = new List<double?>() { 300, 50, 100 }
            };

            data.Datasets = new List<Dataset>();
            data.Datasets.Add(dataset);

            chart.Data = data;

            DataLabels dataLabels = new DataLabels()
            {
                Color = ChartColor.FromHexString("#36A2EB"),
                Formatter = "function(value, context) { return context.dataIndex + ': ' + Math.round(value*100) + '%'; }"
            };

            var options = new Options
            {
                PluginDynamic = new Dictionary<string, object>() { { "plugins", dataLabels } }
            };

            chart.Options = options;

            return chart;
        }
 <script type="text/javascript">
       Chart.register(ChartDataLabels);
       @Html.Raw(pieChart.CreateChartCode("pieChart"));
    </script>

I am using Chart.js v3.9.1 and datalabels 2.1.0 with ChartJSCore 3.3.0.

Thanks, AG