jQuery multiline highcharts

Asked

Viewed 1,069 times

2

I have an MVC application and would like to clarify some questions on how to implement a chart with database data. I am using jQuery to get the values from the database, but did not understand how to take these values and generate a chart using Highcharts, I read a lot on the internet, but it was not clear how to get and put the values on the x and y axis.

For the values of X and Y axes, I am using the following:

Dictionary <decimal, decimal> dataResult = new Dictionary <decimal, decimal> ();

To query the database and assemble the following:

foreach (var item in query) 
{
     dataResult.Add (Convert.ToDecimal (item.valorinicial), Convert.ToDecimal (item.preco)); 

} 

To pass the value:

return Json (dataResult, JsonRequestBehavior.AllowGet);

To generate the Chart, I switched to:

var options = {
                chart: {
                    renderTo: "container",
                },
                series: [{}]
            };



        $.getJSON("/GraficosLev/GetDadosByGraf", { ...parametros passados.... },
            function (data) {
                var chart = new Highcharts.Chart({
                    chart: {
                        renderTo: 'container',
                        ignoreHiddenSeries: false
                    },

                    xAxis: {
                    },


                    series: data
                });
        });

For the search of the data:

Dictionary<decimal, decimal> dataResult = new Dictionary<decimal, decimal>();

        public object GetValuesByGraf(int? idRod, int? idLev, string codLev, string kmIni, string kmFim)
        {
            string tpLev = (from l in db.TIPO_LEVA where l.id == idLev select l.tipo_levantamento).FirstOrDefault();
            //Conta o numero de datas Selecionadas
            string[] codLevant = codLev.Split(',');

            foreach (string i in codLevant)
            {
                //pega os valores do id do codigo de levantmanto para pegar os levantamentos
                int idCodLev = (from l in db.LEV1
                               where l.cod_levantamento == i
                               select l.id).FirstOrDefault();

                if (tpLev =="I")
                {
                    var query = (from iri in db.IRR10
                                      where iri.cod_levantamento_id == idCodLev
                                      select iri);

                    foreach (var item in query)
                    {
                        dataResult.Add(Convert.ToDecimal(item.inicial), Convert.ToDecimal(item.iri));

                    }
                }
            }



            return dataResult;
        }
  • Could you be more specific? You want to understand how to use hightcharts or you want to fix something specific in your code?

  • Dude, I think it would be so much easier for you to look at the demo and do it the same: http://www.highcharts.com/demo/

  • I would like to know how to use hightcharts to generate the chart, but it seems that I am calling the chart before the function get the data.

  • no, he’s just assembling the chart options before the call and after it and adds the series and so yes calls the chart

3 answers

1

would not be "date" instead of "y"

 name: val.key,
 data: val.Value
  • 1

    It’s really gonna make a big difference

  • Didn’t generate the chart even with this change.

0


Observing the responses and comments I noticed that in setting the renderTo is for the container. This really is the id of the element to be Chart?

You can also set your Chart using :

$('#container').highcharts(options);

Use ($('#container')) or go straight to (renderTo: 'container') do the same effect, so just use one of the options and check if the id of the element matches what is in the renderTo.

Your code could look like this:

$(document).ready(function () {
    $("#Submit").click(function (evt) {
     //
     //Algumas Variaveis
     //

        jQuery.get("/ChartLev/GetByGraf", { ...passo os parametros....} }, function (values) {
            $.each(values, function (key, val) {
                data.push({
                    name: val.key,
                    data: val.Value
                })
            });
        });
        var options = {
            chart: {
                backgroundColor: '#ffffff',
                borderColor: '#a2a2a1',
                borderWidth: 0,
                borderRadius: 0,
                type: 'area',
                plotBackgroundColor: '#fffdf6'
            },
            colors: ['#3399FF'],
            legend: {
                enabled: false
            },

            title: {
                text: 'Graf'
            },
            tooltip: {
                borderRadius: 0,
                borderWidth: 0,
                shadow: false,
                style: {
                    fontSize: '7pt',
                    color: '#000000'
                },
                formatter: function() {
                    return this.value
                }
            },
            xAxis: {

                labels: {
                    rotation: -45,
                    x: 0,
                    y: 40,
                    style: {
                        color: '#333333'
                    }
                },
                lineWidth: 1,
                lineColor: '#333333',
                minPadding: 0,
                maxPadding: 0,
                title: {
                    text: ''
                },
                tickInterval: 2,
                tickmarkPlacement: 'on'
            },
            yAxis: {
                gridLineWidth: 0,
                labels: {
                    formatter: function() {
                        return this.value},
                    style: {
                        color: '#333333'
                    }
                },
                lineWidth: 1,
                lineColor: '#333333',
                min: 0,
                minPadding: 0,
                maxPadding: 0,
                title: {
                    text: ''
                }
            },
            series: data
        };
        $('#container').highcharts(options);
    });
});

And in your html:

<div id="container"></div>
  • I would have some example to show ?

  • I’ll edit and put how your code could look

  • Thanks for the help, I’m not able to generate this graphic...

  • Are you giving any error? if yes could paste here for us the error? In case you could not paste here the return that your ajax is generating?

  • Not generating error, just does not appear the line of the graph. Then I do the normal query in the database and it returns the values of two columns. "14,2,5" "14.5,5" , and so on.

  • has how to paste the exact [tag:json] that your ajax generates? Give a look at the browser request and paste the answer the [tag:ajax] so you can see.

  • I will add in the question.

  • I just edited my series look if it modifies what you have. Your series has to be exactly like this [{&#xA; name: 'Tokyo',&#xA; data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6]&#xA;}, {&#xA; name: 'New York',&#xA; data: [-0.2, 0.8, 5.7, 11.3, 17.0, 22.0, 24.8, 24.1, 20.1, 14.1, 8.6, 2.5]&#xA;}, {&#xA; name: 'Berlin',&#xA; data: [-0.9, 0.6, 3.5, 8.4, 13.5, 17.0, 18.6, 17.9, 14.3, 9.0, 3.9, 1.0]&#xA;}, {&#xA; name: 'London',&#xA; data: [3.9, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3, 6.6, 4.8]&#xA;}]

  • I just put the code. But he doesn’t think it generates this way.

  • I understood the problem, but how do I format this way after taking the data in the database ? It would have to be like this [{name: 'data1', date:[[1,2.5],[2,2.6]]}]

  • Take a look here you need to return your data in this format

  • @rysahara this is the [tag:json] here or here to take classes at [tag:Asp.net] to work with [tag:json] if you want other references look at http://www.json.org/

  • Thank you very much for the links, I will study them to see how to implement in the correct way.

  • For nothing if you can give an upvote on the answer and if after studying she has solved your problem, mark as solved, I will thank you very much. :D

  • You can leave.....

Show 10 more comments

0

In your case (starting value and price), the chart could be mounted using this example.

Using this Nuget package.

Controller

public ActionResult BasicBar()
{
    Highcharts chart = new Highcharts("chart")
        .InitChart(new Chart { DefaultSeriesType = ChartTypes.Bar })
        .SetTitle(new Title { Text = "Historic World Population by Region" })
        .SetSubtitle(new Subtitle { Text = "Source: Wikipedia.org" })
        .SetXAxis(new XAxis
            {
                Categories = new[] { "Africa", "America", "Asia", "Europe", "Oceania" },
                Title = new XAxisTitle { Text = string.Empty }
            })
        .SetYAxis(new YAxis
        {
                Min = 0,
                Title = new YAxisTitle
                {
                    Text = "Population (millions)",
                    Align = AxisTitleAligns.High
                }
        })
        .SetTooltip(new Tooltip { Formatter = "function() { return ''+ this.series.name +': '+ this.y +' millions'; }" })
        .SetPlotOptions(new PlotOptions
        {
            Bar = new PlotOptionsBar
            {
                DataLabels = new PlotOptionsBarDataLabels { Enabled = true }
            }
        })
        .SetLegend(new Legend
        {
            Layout = Layouts.Vertical,
            Align = HorizontalAligns.Right,
            VerticalAlign = VerticalAligns.Top,
            X = -100,
            Y = 100,
            Floating = true,
            BorderWidth = 1,
            BackgroundColor = new BackColorOrGradient(ColorTranslator.FromHtml("#FFFFFF")),
            Shadow = true
        })
        .SetCredits(new Credits { Enabled = false })
        .SetSeries(new[]
        {
            new Series { Name = "Year 1800", Data = new Data(new object[] { 107, 31, 635, 203, 2 }) },
            new Series { Name = "Year 1900", Data = new Data(new object[] { 133, 156, 947, 408, 6 }) },
            new Series { Name = "Year 2008", Data = new Data(new object[] { 973, 914, 4054, 732, 34 }) }
        });

        return View(chart);
    }

View

@model DotNet.Highcharts.Highcharts

@{
    ViewBag.Title = "Meu gráfico";
}

<h2>Meu gráfico</h2>

@(Model)

Have more examples in this file.

There’s one more package at the Nuget, the Highcharts.net , but this did not find examples of use, although it is done by a Brazilian and has positive comments on the project page: http://highcharts.codeplex.com/. I think it would be the case to test case by case.

  • But I am passing the values via jquery. I read this example, but am having trouble passing the values to the series, to generate the chart.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.