Search code examples
c#listchartsquickchart

Create a chart with QuickChart in C#


I want to create a graph but I can't send the data from a list, I'm using this library because it allows me to create web links. Can someone help me, I'm using c#. I want to change the months for a list

Chart qc = new Chart();
            qc.Width = 500;
            qc.Height = 300;
            qc.Version = "2.9.4";
            qc.Config = @"{
                          type: 'bar',
                          data: {
                            labels: ['January', 'February', 'March', 'April', 'May'],
                            datasets: [
                              { label: 'Dogs', data: [50, 60, 70, 180, 190] },
                            ],
                          },
                          options: {
                          scales: {
                            xAxes: [
                              {
                                scaleLabel: {
                                  display: true,
                                  fontColor: '#00ff00',
                                  fontSize: 20,
                                  fontStyle: 'bold',
                                  labelString: 'Month',
                                },
                              },
                            ],
                            yAxes: [
                              {
                                scaleLabel: {
                                  display: true,
                                  labelString: '# Users',
                                  fontColor: '#ff0000',
                                  fontSize: 20,
                                  fontStyle: 'bold',
                                },
                              },
                            ]
                          }
                        }
                        }";

Solution

  • You can use string interpolation to dynamically add data to a string, then use String.Join Method to format them to match QuickChart formatting, note that you must use double curly braces to escape the necessary braces

            List<string> labels = new List<string>() { "'Jan'", "'Feb'", "'Jul'", "'Nov'" };
            List<int> data = new List<int>() { 100, 300, 400, 500 };
            Chart qc = new Chart();
    
            qc.Width = 500;
            qc.Height = 300;
            qc.Version = "2.9.4";
            qc.Config = $@"{{
                type: 'bar',
                data: {{
                    labels: [ {string.Join(",", labels)} ],
                    datasets: [{{
                        label: 'Users',
                        data: [ {string.Join(",", data)} ]
                    }}]
                }}
            }}";
    
            Console.WriteLine(qc.GetUrl());
    

    You might need to create your own method to wrap the string data into required quotes.