我想在示例HTML图表中添加我自己的数据。示例数据的javascript代码为:
var data = [];
var visits = 10;
for (var i = 1; i < 50000; i++) {
visits += Math.round((Math.random() < 0.5 ? 1 : -1) * Math.random() * 10);
data.push({
date: new Date(2018, 0, i),
value: visits
});
}
chart.data = data
我用console.log(data)
运行了样本数据的输出,发现样本数据是以下字典列表:
[{"date":"2018-11-10T05:00:00.000Z","value":-459},
{"date":"2018-11-11T05:00:00.000Z","value":-459},
{"date":"2018-11-12T05:00:00.000Z","value":-464},
...
{"date":"2020-11-22T05:00:00.000Z","value":-493}]
我使用pandas
创建了一个字典列表作为自己的数据。我更改了我自己的数据以匹配上述样本数据列表的格式,以下列表是我自己的资料:
rnow =
[{'date': '01/02/2020', 'value': 13},
{'date': '01/03/2020', 'value': 2},
{'date': '01/06/2020', 'value': 5},
...
{'date': '01/07/2020', 'value': 6}]
我意识到日期格式与示例数据不同。我使用以下代码将日期格式更改为yyyy-mm-dd。
dfrnow['date'] = pd.to_datetime(dfrnow.date)
rnow = dfrnow.to_dict('records')
现在我的数据显示为:
rnow =
[{'date': Timestamp('2020-01-02 00:00:00'), 'value': 13},
{'date': Timestamp('2020-01-03 00:00:00'), 'value': 2},
{'date': Timestamp('2020-01-06 00:00:00'), 'value': 5},
...
{'date': Timestamp('2020-01-07 00:00:00'), 'value': 6}]
当我用自己的数据替换示例数据时,图表不会显示任何数据。那是因为它有这个";时间戳";我的列表中显示的东西,我应该如何删除它?或者还有其他更好的方法可以用来转换我的日期吗?
(以下代码是这个模板图的所有js代码。我在这里列出了它们,以防我遗漏了什么。(
var chart = am4core.create("chartdiv", am4charts.XYChart);
chart.paddingRight = 20;
var data = [];
var visits = 10;
for (var i = 1; i < 50000; i++) {
visits += Math.round((Math.random() < 0.5 ? 1 : -1) * Math.random() * 10);
data.push({
date: new Date(2018, 0, i),
value: visits
});
}
chart.data = {{rnow}};
var dateAxis = chart.xAxes.push(new am4charts.DateAxis());
dateAxis.renderer.grid.template.location = 0;
dateAxis.minZoomCount = 5;
dateAxis.groupData = true;
dateAxis.groupCount = 500;
var valueAxis = chart.yAxes.push(new am4charts.ValueAxis());
var series = chart.series.push(new am4charts.LineSeries());
series.dataFields.dateX = "date";
series.dataFields.valueY = "value";
series.tooltipText = "{valueY}";
series.tooltip.pointerOrientation = "vertical";
series.tooltip.background.fillOpacity = 0.5;
chart.cursor = new am4charts.XYCursor();
chart.cursor.xAxis = dateAxis;
var scrollbarX = new am4core.Scrollbar();
scrollbarX.marginBottom = 20;
chart.scrollbarX = scrollbarX;
var selector = new am4plugins_rangeSelector.DateAxisRangeSelector();
selector.container = document.getElementById("selectordiv");
selector.axis = dateAxis;
我通过解决了它
rnow = dfrnow.to_dict('records')
def new_date(date):
return datetime.strptime(date, '%m/%d/%Y').strftime('%Y-%m-%dT00:00:00Z')
for i in range (len(rnow)):
rnow[i]['date'] = new_date(rnow[i]['date'])