Is there a wey to use a dictionary object as data in echarts? - echarts

I'm using echarts to plot my data. Then I have two data which has different time(which is X axis),and I want to plot them in one picture. But I found that echart's data just can be a array,So this two data's value will not plot right as their real time.
So my questions is that can echarts use a dictionary data?which use time as key.Then the two data will plot at right time.

try using the type 'time' on xAxis. See also the new way to pass data to the chart using dataset:
var myChart = echarts.init(document.getElementById('main'));
// format with arrays:
var source = [
['2019-08-28T07:01:00+02:00', 127.7],
['2019-08-28T07:02:00+02:00', 148.0],
['2019-08-28T07:03:00+02:00', 1180.4],
['2019-08-28T07:04:00+02:00', 117.9]
]
// format with objects:
// var source = [
// { datetime: '2019-08-28T07:01:00+02:00', value: 127.7 },
// { datetime: '2019-08-28T07:02:00+02:00', value: 148.0 },
// { datetime: '2019-08-28T07:03:00+02:00', value: 1180.4 },
// { datetime: '2019-08-28T07:04:00+02:00', value: 117.9 }
// ];
option = {
dataset: {
dimensions: ['datetime', 'value'],
source: source
},
xAxis: {
type: 'time'
},
yAxis: {
type: 'value'
},
series: [{
name: 'series1',
type: 'line',
}]
}
myChart.setOption(option);

Related

Changing data symbol when using ECharts dataset format

ECharts allows defining different symbol for each data point when using series.data option like in this example:
option = {
xAxis: {
type: 'time'
},
yAxis: {
type: 'value'
},
series: [
{
symbolSize: 50,
data: [
{ value: ['2023-01-01T15:00:00Z', 10], symbol: 'circle' },
{ value: ['2023-01-01T16:00:00Z', 20], symbol: 'rect' },
{ value: ['2023-01-01T17:00:00Z', 15], symbol: 'triangle' }
],
type: 'line'
}
]
};
This could be used e.g. to display weather symbol in a weather forecast chart. The example defines data under series, however it seems to be an older approach and now it is recommended to use datasets instead.
How to set the symbol per datapoint when providing data in dataset.source?
series.symbol can be a callback function which can access the data from dataset and return different symbol for each data point:
If symbols needs to be different, you can set with callback function
in the following format:
(value: Array|number, params: Object) => string The first parameter
value is the value in data, and the second parameter params is the
rest parameters of data item.
So using dataset and callback, the code becomes:
option = {
dataset: {
source: [
// Each entry has 3rd value set to the symbol name.
['2023-01-01T15:00:00Z', 10, 'circle'],
['2023-01-01T16:00:00Z', 20, 'rect'],
['2023-01-01T17:00:00Z', 15, 'triangle'],
]
},
xAxis: {
type: 'time'
},
yAxis: {
type: 'value'
},
series: [
{
symbolSize: 50,
// The first parameter 'value' is the entry in dataset.
// 3rd value (value[2]) is the symbol name.
symbol: (value, params) => value[2],
type: 'line'
}
]
};

Question about colorBy after data sorting

In this example with universalTransition turned on, after the pie chart of colorBy:'data' is sorted, it is inconsistent with the corresponding relationship between labels and colors in the bar chart, how to make their colors consistent.
Makepie will be out of service on February 15, you can run follow code on ECharts examples editor.
const dataset = {
dimensions: ['name', 'score'],
source: [
['Hannah Krause', 314],
['Zhao Qian', 351],
]
};
const pieOption = {
// dataset: [dataset],
// 顺序排序数据
dataset: [dataset].concat({
transform: {
type: 'sort',
config: { dimension: 'score', order: 'desc' },
},
}),
series: [
{
type: 'pie',
// 通过 id 关联需要过渡动画的系列
id: 'Score',
radius: [0, '50%'],
universalTransition: true,
animationDurationUpdate: 1000,
// 取排序后的数据
datasetIndex: 1,
}
]
};
const barOption = {
dataset: [dataset],
xAxis: {
type: 'category'
},
yAxis: {},
series: [
{
type: 'bar',
// 通过 id 关联需要过渡动画的系列
id: 'Score',
// 每个数据都是用不同的颜色
colorBy: 'data',
encode: { x: 'name', y: 'score' },
universalTransition: true,
animationDurationUpdate: 1000
}
]
};
option = barOption;
setInterval(() => {
option = option === pieOption ? barOption : pieOption;
// 使用 notMerge 的形式可以移除坐标轴
myChart.setOption(option, true);
}, 2000);
Your dataset order by 'desc' on pie chart.
but it's not used on bar chart.
Maybe your two charts should be sorted in the same order
dataset: [dataset].concat({
transform: {
type: 'sort',
config: { dimension: 'score', order: 'desc' },
},
}),

How to use Chart.js to draw mixed Financial / Candlestick and Bar Chart?

I'm trying to make a a combination of a candlestick chart (representing stock data) and a bar chart (representing volume).
I already have them displayed on one chart but the display and layout I'm having trouble with.
For one, the candlestick and bar data are placed side-by-side rather than stacked on top of each other. Another error is the scale of the volume data for the bar chart is not represented properly in the y-axis (which uses data from candlesticks as basis).
Here is my current code to render the chart:
chart = new Chart(ctx, {
type: 'candlestick',
data: {
labels: labelsData,
datasets: [{
label: "My Data",
data: chartData
},
{
label: 'Volume',
data: volData,
type: 'bar'
}]
}
});
labelsData contains the Date values for each item entry
chartData contains JSON object with c,h,l,o,t (close,high,low,open,date) to
represent stock data for each item entry
volData is an array containing numbers to represent volume for each item entry
What should I add to make the candlesticks and bars placed on the same column, as well as have the bars have their own scale so they do not overshoot the height of the chart?
It seems you need to scale the volume data since it's two different value units in Y,
It seems like currentlty there isn't support for this in chartJs I created a feature request, follow the link to see the two issues that were closed due to this.
https://github.com/apexcharts/apexcharts.js/issues/2068
With default configuration you're not easily able to add barcharts.
Here is steps you need to do;
Base config:
const config = {
// type: 'candlestick', // you must remove this, this option is braking the chart
data: {
datasets: []
},
options: {
parsing: false, // must be here, solves another stupid problem
spanGaps: true, // for better performance
animation: false, // for better performance
pointRadius: 0, // for better performance
plugins: {
title: {
display: false,
text: 'Fiyat Grafiği'
},
},
responsive: true,
maintainAspectRatio: false,
scales: {
x: {
type: 'timeseries',
},
y: {
type: 'linear',
},
volume: {
type: 'linear',
beginAtZero: true,
position: 'right',
max: maxVolume * 10, // maxVolume should be the maximum number of volumes
grid: {
display: false, // for better presentation
},
ticks: {
display: false, // for better presentation
},
}
},
interaction: {
intersect: false,
mode: 'index',
},
}
};
Second step is preparing the datasets;
let dataSets = [
{
type: 'candlestick', // this must stay
label: 'Financial Graph',
data: data['klines'].map(function (kline) {
return {
'x': moment(kline['from']),
'o': kline['open_price'],
'c': kline['close_price'],
'h': kline['high_price'],
'l': kline['low_price']
};
}),
color: {
up: 'rgb(26, 152, 129)', // those colors are better than defaults
down: 'rgb(239, 57, 74)', // those colors are better than defaults
unchanged: '#999', // those colors are better than defaults
},
borderColor: {
up: 'rgb(26, 152, 129)',
down: 'rgb(239, 57, 74)',
unchanged: '#999',
},
order: 10,
yAxisID: 'y', // this must stay
},
{
type: 'bar',
label: 'Volume',
data: data['klines'].map(function (kline) {
return {
'x': moment(kline['from']), // i used moment, feel free to use your own time library
'y': kline.quote_asset_volume,
}
}),
backgroundColor: data['klines'].map(function (kline) {
return kline.open_price < kline.close_price ? 'rgb(26, 152, 129)' : 'rgb(239, 57, 74)' // for better presentation
}),
borderColor: '#fff',
borderWidth: 1,
order: 12,
yAxisID: 'volume', // this must stay
barPercentage: 0.5, // this must stay
barThickness: 6, // this must stay
maxBarThickness: 8, // this must stay
},
]
Result;

Merging two datasets with different dates/UNIX timestamps

I'm trying to make a chart that shows the trade volumes for the currencies CAD and DKK:
https://jsfiddle.net/askhflajsf/g7mht8tt/
Using data from these files:
http://api.bitcoincharts.com/v1/csv/localbtcCAD.csv.gz
http://api.bitcoincharts.com/v1/csv/localbtcDKK.csv.gz
But, how do I deal with the fact that these datasets have different dates/UNIX timestamps? My chart above has DKK's data "forced into" CAD's timestamps -- but this can't be right can it? What should I do?
Note: The below snippet doesn't have the full data due to StackOverflow's body limit.
// Disable pointers
Chart.defaults.global.elements.point.radius = 0;
Chart.defaults.global.elements.point.hoverRadius = 0;
var myChartData = {
// Timestamps from http://api.bitcoincharts.com/v1/csv/localbtcCAD.csv.gz
labels: [1363085391, 1363088879, 1363120475, 1363132522, 1363214378],
// Timestamps from http://api.bitcoincharts.com/v1/csv/localbtcDKK.csv.gz
//labels: [1366383202, 1366471506, 1368121200, 1375783458, 1375953845],
datasets: [{
label: "CAD",
borderColor: "#FF0000",
fill: false,
borderWidth: 1,
data: [5.432200000000, 4.981800000000, 1.768000000000, 1.000000000000, 4.000000000000]
},
{
label: "DKK",
borderColor: "#000000",
fill: false,
borderWidth: 1,
data: [1.000000000000, 2.700000000000, 2.187400000000, 1.000000000000, 4.000000000000]
}
]
};
var ctx = document.getElementById("mychart").getContext("2d");
new Chart(ctx, {
type: 'line',
data: myChartData,
options: {
scales: {
xAxes: [{
type: "time",
ticks: {
minRotation: 90
}
}]
}
}
});
<script src="https://rawgit.com/chartjs/chartjs.github.io/master/dist/master/Chart.bundle.min.js"></script>
<canvas id="mychart"></canvas>

SAPUI5: Issue in getting datetime values from HANA db to Chart

I am trying to get the datetime values and aggregated
response time from hana database to a bar chart.
I have done the aggregation in .xsodata file as :
{
service namespace "excercise.services" {
"ABC"."XYZ" as "sample" key generate local "Key"
aggregates always(SUM of "respti" ) ;
}
}
I am getting aggregated response time values but it is not
getting synchronized with the respective date values .
Please help me on getting the correct values.
Here is the view.js file:
{
var oModel = sap.ui.model.odata.ODataModel('.xsodata/', false);
var oDataset = new sap.viz.ui5.data.FlattenedDataset({
dimensions: [{
axis: 1,
name: 'Time Instance',
value: {
path: "ts",
formatter: function(fValue) {
jQuery.sap.require("sap.ui.core.format.DateFormat");
var oDateFormat = sap.ui.core.format.DateFormat.getDateTimeInstance();
return oDateFormat.format(new Date(fValue));
}
},
},
],
measures: [{
name: 'Response Time',
value: '{respti}'
}],
data: {
path: "/sample",
filters: [
new sap.ui.model.Filter("inst", sap.ui.model.FilterOperator.EQ, "instance")
],
parameters: {
select: 'ts,respti'
},
}
});
}
you may want to try
dimensions: [{
axis: 1,
name: 'Time Instance',
value: {
path: "ts",
formatter: function(fValue) {
if(fValue){
jQuery.sap.require("sap.ui.core.format.DateFormat");
var oDateFormat = sap.ui.core.format.DateFormat.getDateTimeInstance();
return oDateFormat.format(new Date(fValue));
} else {
return fValue;
}
}
},
}],
what is the format of respti, you may want to format that also, using a D3 formatter maybe simplest way