给定轴上的所有系列都必须具有相同的数据类型—错误消息,同时在图表上显示数据

时间:2022-12-25 16:11:10

I am trying to display data from my database in MVC application using google charts. When I display "int" format it works fine, but when I want to change to for example "datetime" type I get the error message: "All series on a given axis must be of the same data type". Here is my sample database: Database

我正在尝试使用谷歌图表在MVC应用程序中显示来自我的数据库的数据。当我显示“int”格式时,它工作得很好,但是当我想要更改为“datetime”类型时,我将得到错误消息:“给定轴上的所有系列必须是相同的数据类型”。这是我的样本数据库:数据库。

Controller code:

控制器代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace GoogleProba.Controllers
{
public class GoogleChartController : Controller
{
    // GET: GoogleChart
    public ActionResult Column()
    {
        return View();
    }
    public JsonResult GetSalesData()
    {
        List<SalesData> sd = new List<SalesData>();
        using (MyDatabaseEntities dc = new MyDatabaseEntities())
        {
            sd = dc.SalesData.OrderBy(a => a.Data).ToList();
        }

        var chartData = new object[sd.Count + 1];
        chartData[0] = new object[]{
                "Data",
                "Electronics",
                "Book And Media",
                "Home And Kitchen"
            };
        int j = 0;
        foreach (var i in sd)
        {
            j++;
            chartData[j] = new object[] { i.Data, i.Electronics, i.BookAndMedia, i.HomeAndKitch };
        }

        return new JsonResult { Data = chartData, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
    }
}
}

View code(updated):

视图代码(更新):

@{
ViewBag.Title = "Column";
 }



 <div id="visualization" style="width:600px; height:300px">

 </div>
 <script src="https://www.gstatic.com/charts/loader.js"></script>
 <script type="text/javascript"    src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
 @section Scripts{
 <script>
  google.charts.load('current', {
  callback: function () {
    //Load Data Here
    var chartData = null;
    $.ajax({
        url: '/GoogleChart/GetSalesData',
        type: 'GET',
        dataType: 'json',
        data: ''
    }).done(function (d) {
        drawChart(d);
        console.log(JSON.stringify(d))
    }).fail(function (jq, text, errMsg) {
        console.log(errMsg);
    });
  },
  packages:['corechart']
  });

 function drawChart(d) {
// process date column
d.forEach(function (row, index) {
  if (index === 0) {
    return;
  }
  row[0] = row[0].replace('/', 'new ');
  row[0] = row[0].replace('/', '');
  row[0] = eval(row[0]);

});

data = google.visualization.arrayToDataTable(d);

var view = new google.visualization.DataView(data);
view.setColumns([0, {
    type: 'datetime',
    label: data.getColumnLabel(0),
    calc: function () { return 0; }
}, {
    type: 'number',
    label: data.getColumnLabel(1),
    calc: function () { return 0; }
}, {
    type: 'number',
    label: data.getColumnLabel(2),
    calc: function () { return 0; }
}, {
    type: 'number',
    label: data.getColumnLabel(3),
    calc: function () { return 0; }
}]);

var chart = new google.visualization.LineChart(document.getElementById('visualization'));
var options = {
    title: 'Sales Report',
    legend: 'bottom',
    hAxis: {
        title: 'year',
        format: '#'
    },
    vAxis: {
        minValue: 0,
        maxValue: 1000000,
        title: 'Sales Amount'
    },
    chartArea: {
        left:100, top: 50, width:'70%', height: '50%'
    },
    animation: {
        duration: 1000
    }
};

google.visualization.events.addOneTimeListener(chart, 'ready', function () {
    chart.draw(data, options);
});

chart.draw(view, options);
 }
</script>

 }

My data from the log: [["Data","Electronics","Book And Media","Home And Kitchen"],["2016-01-31T23:00:00.000Z",345000,76666,66777],["2016-03-05T23:00:00.000Z",567000,94000,234000],["2016-05-06T22:00:00.000Z",234555,55555,678900],["2016-06-02T22:00:00.000Z",455555,555555,567000]]

我的数据来自于日志:["数据","电子","书与媒体","家庭与厨房"],[" 2016-01-31t23:00 - 0000 z ",345000,76666,66777],[" 2016-03-05-07-00000z ",567000,94000,234000],[" 2016-05-05-06t22:00 . 0000 z ",234555,55555,678900],[" 2016-06-02t22:00 ", 455555555555555,567000]]

When I put "Year" from database on X axis it works very pretty but when I change to display "Data" it doesn't works, anyone can help me with that?

当我从X轴上的数据库中输入"Year"时它非常漂亮,但当我改变显示"数据"它不起作用时,有人能帮我吗?

1 个解决方案

#1


1  

first, since you're totaly newbie...

首先,既然你是个新手……

it's recommended to use loader.js to load the chart library, vs. jsapi

建议使用loader。加载图表库,而不是jsapi

<script src="https://www.gstatic.com/charts/loader.js"></script>

< script src = " https://www.gstatic.com/charts/loader.js " > < /脚本>

according to the release notes...

根据发布说明……

The version of Google Charts that remains available via the jsapi loader is no longer being updated consistently. Please use the new gstatic loader from now on.

通过jsapi加载器提供的谷歌图表的版本不再不断更新。请从现在开始使用新的gstatic加载程序。

this will only change the load statement, see snippet below for specifics...

这只会改变load语句,具体细节见下面的代码片段…


next, to make it easy on google, the json date needs to formatted a certain way...

接下来,为了简化谷歌,json日期需要以某种方式进行格式化……

"Date(year, month, day, hours, minutes, days, seconds, milliseconds)"

日期(年、月、日、小时、分钟、天、秒、毫秒)

e.g. --> "Date(2016, 11, 21)" -- or -- "Date(2016, 11, 21, 20, 48, 18, 122)" -- etc...

例:>“日期(2016,11,21)”——或——“日期(2016年、11、21、20、48、18、122)”——等等……


however, I'm not much help with c#

然而,我对c#并不是很有帮助

as such, the following script will convert the date on the client using javascript

因此,下面的脚本将使用javascript在客户机上转换日期

(not recommended for large data sets)

(大数据集不推荐)


javascript can use the integer to get the proper date, just needs to be in a different format

javascript可以使用整数获得合适的日期,只需使用不同的格式

-- convert first column in array to actual date

——将数组中的第一列转换为实际日期

from: "/Date(1454281200000)/"

来自:/日期(1454281200000)/

to: new Date(1454281200000)

:新日期(1454281200000)

// replace first forward slash (/) with 'new'
row[0] = row[0].replace('/', 'new ');

// remove second forward slash (/)
row[0] = row[0].replace('/', '');

// evaluate the string to an actual date
row[0] = eval(row[0]);

see following working snippet...

看到以下工作片段…

google.charts.load('current', {
  callback: function () {
    var rawData = [
      ["Data","Electronics","Book And Media","Home And Kitchen"],
      ["/Date(1454281200000)/",345000,76666,66777],
      ["/Date(1457218800000)/",567000,94000,234000],
      ["/Date(1462572000000)/",234555,55555,678900],
      ["/Date(1464904800000)/",455555,555555,567000]
    ];

    rawData.forEach(function (row, index) {
      // skip column labels
      if (index === 0) {
        return;
      }
      row[0] = row[0].replace('/', 'new ');
      row[0] = row[0].replace('/', '');
      row[0] = eval(row[0]);
    });

    var data = google.visualization.arrayToDataTable(rawData);

    var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
    chart.draw(data, {
      hAxis: {
        format: 'MMM yyyy'
      }
    });
  },
  packages:['corechart']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

EDIT

编辑

integrating into the code from the question,

整合到问题的代码中,

you can rely on the google callback to know when the page is ready
instead of --> $(document).ready

您可以依赖谷歌回调来知道页面何时准备好,而不是——> $(document).ready

there are a couple minor other changes, including addOneTimeListener

还有一些其他的小更改,包括addOneTimeListener

<script>
  google.charts.load('current', {
      callback: function () {
        //Load Data Here
        var chartData = null;
        $.ajax({
            url: '/GoogleChart/GetSalesData',
            type: 'GET',
            dataType: 'json',
            data: ''
        }).done(function (d) {
            drawChart(d);
        }).fail(function (jq, text, errMsg) {
            console.log(errMsg);
        });
      },
      packages:['corechart']
  });

  function drawChart(d) {
    // process date column
    d.forEach(function (row, index) {
      if (index === 0) {
        return;
      }
      row[0] = row[0].replace('/', 'new ');
      row[0] = row[0].replace('/', '');
      row[0] = eval(row[0]);
    });

    data = google.visualization.arrayToDataTable(d);

    var view = new google.visualization.DataView(data);
    view.setColumns([0, {
        type: 'datetime',
        label: data.getColumnLabel(0),
        calc: function () { return 0; }
    }, {
        type: 'number',
        label: data.getColumnLabel(1),
        calc: function () { return 0; }
    }, {
        type: 'number',
        label: data.getColumnLabel(2),
        calc: function () { return 0; }
    }, {
        type: 'number',
        label: data.getColumnLabel(3),
        calc: function () { return 0; }
    }]);

    var chart = new google.visualization.LineChart(document.getElementById('visualization'));
    var options = {
        title: 'Sales Report',
        legend: 'bottom',
        hAxis: {
            title: 'year',
            format: '#'
        },
        vAxis: {
            minValue: 0,
            maxValue: 1000000,
            title: 'Sales Amount'
        },
        chartArea: {
            left:100, top: 50, width:'70%', height: '50%'
        },
        animation: {
            duration: 1000
        }
    };

    google.visualization.events.addOneTimeListener(chart, 'ready', function () {
        chart.draw(data, options);
    });

    chart.draw(view, options);
  }
</script>

#1


1  

first, since you're totaly newbie...

首先,既然你是个新手……

it's recommended to use loader.js to load the chart library, vs. jsapi

建议使用loader。加载图表库,而不是jsapi

<script src="https://www.gstatic.com/charts/loader.js"></script>

< script src = " https://www.gstatic.com/charts/loader.js " > < /脚本>

according to the release notes...

根据发布说明……

The version of Google Charts that remains available via the jsapi loader is no longer being updated consistently. Please use the new gstatic loader from now on.

通过jsapi加载器提供的谷歌图表的版本不再不断更新。请从现在开始使用新的gstatic加载程序。

this will only change the load statement, see snippet below for specifics...

这只会改变load语句,具体细节见下面的代码片段…


next, to make it easy on google, the json date needs to formatted a certain way...

接下来,为了简化谷歌,json日期需要以某种方式进行格式化……

"Date(year, month, day, hours, minutes, days, seconds, milliseconds)"

日期(年、月、日、小时、分钟、天、秒、毫秒)

e.g. --> "Date(2016, 11, 21)" -- or -- "Date(2016, 11, 21, 20, 48, 18, 122)" -- etc...

例:>“日期(2016,11,21)”——或——“日期(2016年、11、21、20、48、18、122)”——等等……


however, I'm not much help with c#

然而,我对c#并不是很有帮助

as such, the following script will convert the date on the client using javascript

因此,下面的脚本将使用javascript在客户机上转换日期

(not recommended for large data sets)

(大数据集不推荐)


javascript can use the integer to get the proper date, just needs to be in a different format

javascript可以使用整数获得合适的日期,只需使用不同的格式

-- convert first column in array to actual date

——将数组中的第一列转换为实际日期

from: "/Date(1454281200000)/"

来自:/日期(1454281200000)/

to: new Date(1454281200000)

:新日期(1454281200000)

// replace first forward slash (/) with 'new'
row[0] = row[0].replace('/', 'new ');

// remove second forward slash (/)
row[0] = row[0].replace('/', '');

// evaluate the string to an actual date
row[0] = eval(row[0]);

see following working snippet...

看到以下工作片段…

google.charts.load('current', {
  callback: function () {
    var rawData = [
      ["Data","Electronics","Book And Media","Home And Kitchen"],
      ["/Date(1454281200000)/",345000,76666,66777],
      ["/Date(1457218800000)/",567000,94000,234000],
      ["/Date(1462572000000)/",234555,55555,678900],
      ["/Date(1464904800000)/",455555,555555,567000]
    ];

    rawData.forEach(function (row, index) {
      // skip column labels
      if (index === 0) {
        return;
      }
      row[0] = row[0].replace('/', 'new ');
      row[0] = row[0].replace('/', '');
      row[0] = eval(row[0]);
    });

    var data = google.visualization.arrayToDataTable(rawData);

    var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
    chart.draw(data, {
      hAxis: {
        format: 'MMM yyyy'
      }
    });
  },
  packages:['corechart']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

EDIT

编辑

integrating into the code from the question,

整合到问题的代码中,

you can rely on the google callback to know when the page is ready
instead of --> $(document).ready

您可以依赖谷歌回调来知道页面何时准备好,而不是——> $(document).ready

there are a couple minor other changes, including addOneTimeListener

还有一些其他的小更改,包括addOneTimeListener

<script>
  google.charts.load('current', {
      callback: function () {
        //Load Data Here
        var chartData = null;
        $.ajax({
            url: '/GoogleChart/GetSalesData',
            type: 'GET',
            dataType: 'json',
            data: ''
        }).done(function (d) {
            drawChart(d);
        }).fail(function (jq, text, errMsg) {
            console.log(errMsg);
        });
      },
      packages:['corechart']
  });

  function drawChart(d) {
    // process date column
    d.forEach(function (row, index) {
      if (index === 0) {
        return;
      }
      row[0] = row[0].replace('/', 'new ');
      row[0] = row[0].replace('/', '');
      row[0] = eval(row[0]);
    });

    data = google.visualization.arrayToDataTable(d);

    var view = new google.visualization.DataView(data);
    view.setColumns([0, {
        type: 'datetime',
        label: data.getColumnLabel(0),
        calc: function () { return 0; }
    }, {
        type: 'number',
        label: data.getColumnLabel(1),
        calc: function () { return 0; }
    }, {
        type: 'number',
        label: data.getColumnLabel(2),
        calc: function () { return 0; }
    }, {
        type: 'number',
        label: data.getColumnLabel(3),
        calc: function () { return 0; }
    }]);

    var chart = new google.visualization.LineChart(document.getElementById('visualization'));
    var options = {
        title: 'Sales Report',
        legend: 'bottom',
        hAxis: {
            title: 'year',
            format: '#'
        },
        vAxis: {
            minValue: 0,
            maxValue: 1000000,
            title: 'Sales Amount'
        },
        chartArea: {
            left:100, top: 50, width:'70%', height: '50%'
        },
        animation: {
            duration: 1000
        }
    };

    google.visualization.events.addOneTimeListener(chart, 'ready', function () {
        chart.draw(data, options);
    });

    chart.draw(view, options);
  }
</script>