echarts stacked bar chart with time xaxis - echarts

Can someone check my chart options and suggest a way to make the time xaxis behave correctly? I've tried with timestamps, dates, timestamps / 1000 and nothing looks right
let sales = [
0,84,5,3,2,1,0,0,3,6
]
let listings = [
1,297,23,5,8,6,9,3,6,19
]
let ps = [
1663084060653,
1663089644329,
1663095228005,
1663100811680,
1663106395356,
1663111979032,
1663117562708,
1663123146384,
1663128730059,
1663134313735
]
let color = "red"
option = {
textStyle: {
color
},
legend: {
textStyle: {
color
},
},
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'shadow'
}
},
grid: {
left: '3%',
right: '4%',
bottom: '3%',
containLabel: true
},
xAxis: [
{
type: 'time',
data: ps,
// axisLabel: {
// formatter: ts => new Date(ts).toTimeString().replace(/ .*/, '')
// }
}
],
yAxis: [
{
// type: 'value'
}
],
series: [
{
name: 'Sales',
type: 'bar',
stack: 'Ad',
emphasis: {
focus: 'series'
},
data: sales
},
{
name: "Listings",
type: 'bar',
stack: 'Ad',
emphasis: {
focus: 'series'
},
data: listings
}
]
}

Your series (listings & sales here) have to have a [date, value] format. Also, you'll have to remove data from xAxis as it will automatically follow the dates that are given in the series.
So, in your example :
//convert listings & sales to a list of [date, value]
listings = listings.map((value, index) => {
return [ps[index], value]
})
sales = sales.map((value, index) => {
return [ps[index], value]
})
xAxis: [
{
type: 'time',
//data: ps, <--- remove this line
}
],

Related

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' },
},
}),

Apache ECharts: Rotated labels get cropped

I'm trying to use rotated labels in my graph. However, the labels are getting cropped. How can I make more space in the bottom so that the labels can fit?
options = {
xAxis: {
type: "category",
data: axis,
axisLabel: {
show: true,
interval: 0,
rotate: 45,
},
axisTick: {
show: true,
interval: 0
}
},
yAxis: {
type: "value",
data: axis,
min: 1,
minInterval: 1,
maxInterval: 1,
max: 15,
axisTick: {
interval: 1
}
},
series: [
{
type: "bar",
stack: "minmax",
itemStyle: {
normal: {
color: "rgba(0,0,0,0)"
}
},
data: maxs
},
{
type: "bar",
stack: "minmax",
data: mins,
itemStyle: { color: "#63869e" }
},
{
symbolSize: 20,
data: scatter,
type: "scatter",
itemStyle: { color: "black" },
},
]
};
To contain the label you can use:
options = {
grid: {
containLabel: true,
}
}
Space can be added with grid option bottom:
options = {
grid: {
bottom: 100,
}
}

How to update the echarts plot theme dynamicaly

Can someone explain to me how to toggle from light to dark theme without reloading the page??
I have this code that checks if the theme is light or dark and I want to change the theme dynamically base on the theme.
my code so far
initECharts(days: any, hours: any, data: any) {
if (this._chart) {
this._chart.clear();
this._chart = null;
}
// console.log('days: ', this.days);
// console.log('hours: ', this.hours);
// console.log('values: ', this.values);
data = this.reconstructData(days, hours, data);
// const x: any = document.getElementById('main');
const theme = (this._themeService.theme === 'dark') ? 'dark' : 'light';
console.log('theme', theme);
const domEl: any = this.main.nativeElement;
this._chart = echarts.init(domEl, theme);
// specify chart configuration item and data
const option: any = {
tooltip: {
position: 'top'
},
animation: false,
grid: {
height: '50%',
y: '10%'
},
xAxis: {
type: 'category',
data: hours,
splitArea: {
show: true
},
nameTextStyle: {
color: 'red'
}
},
yAxis: {
type: 'category',
data: days,
splitArea: {
show: true
}
},
visualMap: {
min: 0,
max: 10,
calculable: true,
orient: 'horizontal',
left: 'center',
bottom: '15%'
},
series: [{
name: 'Punch Card',
type: 'heatmap',
data: data,
label: {
normal: {
show: true
}
},
itemStyle: {
emphasis: {
shadowBlur: 10,
shadowColor: 'rgba(0, 0, 0, 0.5)'
}
}
}]
};
// use configuration item and data specified to show chart
this._chart.setOption(option);
}
Ok, I found it.
every time you want to update the theme dynamically example a button or an observable or Promise, you must call this method
echarts.dispose(this._chart);
then you call the initMethod, example:
this.initECharts();
The init method can look like this in my case.
initECharts(days: any, hours: any, data: any) {
data = this.reconstructData(days, hours, data);
// const x: any = document.getElementById('main');
const theme = (this._themeService.theme === 'dark') ? 'dark' : 'light';
console.log('theme', theme);
const domEl: any = this.main.nativeElement;
this._chart = echarts.init(domEl, theme);
// specify chart configuration item and data
const option: any = {
tooltip: {
position: 'top'
},
animation: false,
grid: {
height: '50%',
y: '10%'
},
xAxis: {
type: 'category',
data: hours,
splitArea: {
show: true
},
nameTextStyle: {
color: 'red'
}
},
yAxis: {
type: 'category',
data: days,
splitArea: {
show: true
}
},
visualMap: {
min: 0,
max: 10,
calculable: true,
orient: 'horizontal',
left: 'center',
bottom: '15%'
},
series: [{
name: 'Punch Card',
type: 'heatmap',
data: data,
label: {
normal: {
show: true
}
},
itemStyle: {
emphasis: {
shadowBlur: 10,
shadowColor: 'rgba(0, 0, 0, 0.5)'
}
}
}]
};
// use configuration item and data specified to show chart
this._chart.setOption(option);
}

ECharts Baidu how to display labels in negative value as positive value?

I am using ECharts Baidu to generate charts. I am using a tornado chart to display the force of left and right arm. The force of the left arm is displayed at the left side and right arm at the right side. Is there a way display the negative value of the label and the axis as positive? I can always hide the axis value so as long as the solution can make the graph to display negative as positive label, I will mark it as solution.
https://echarts.baidu.com/echarts2/doc/example/bar5.html#-en
var option= {
title: {
},
grid: {
top: '10%',
bottom: '25%',
left: '20%',
right: '10%',
},
tooltip: { triggerOn: 'click' },
xAxis: [
{
type: 'value',
name: 'Newton',
nameLocation: 'center',
nameTextStyle: {
padding: 10
},
}
],
yAxis: [
{
axisTick: { show: false },
data: ['FEB']
}
],
barWidth: 40,
series: [
{
type: 'bar',
stack: 'feb',
label: {
normal: {
show: true,
position: 'top',
}
},
data: [{ value: Number(data2[0].left) * -1 }], //the value is from the ajax call
itemStyle: { color: 'gray' }
},
{
type: 'bar',
stack: 'feb',
label: {
normal: {
show: true,
position: 'top'
}
},
data: [Number(data2[0].right)],
itemStyle: { color: '#F26718' },
},
],
textStyle: {
fontWeight: 'bold',
color: 'black'
}
}
chart.setOption(option);
})
try with this:
label: {
normal: {
show: true,
position: 'top',
formatter: function (params) {
return Math.abs(params.value[1]);
}
}
}
this example assumes that the data you passed to the chart is an array like [x, y]. if your input data is different, put a breakpoint inside the formatter function e see how "params" is structured.

Kendo grid date column not formatting

I have a KendoGrid like below and when I run the application, I'm not getting the expected format for date column.
$("#empGrid").kendoGrid({
dataSource: {
data: empModel.Value,
pageSize: 10
},
columns: [
{
field: "Name",
width: 90,
title: "Name"
},
{
field: "DOJ",
width: 90,
title: "DOJ",
type: "date",
format:"{0:MM-dd-yyyy}"
}
]
});
When I run this, I'm getting "2013-07-02T00:00:00Z" in DOJ column. Why it is not formatting? Any idea?
I found this piece of information and got it to work correctly. The data given to me was in string format so I needed to parse the string using kendo.parseDate before formatting it with kendo.toString.
columns: [
{
field: "FirstName",
title: "FIRST NAME"
},
{
field: "LastName",
title: "LAST NAME"
},
{
field: "DateOfBirth",
title: "DATE OF BIRTH",
template: "#= kendo.toString(kendo.parseDate(DateOfBirth, 'yyyy-MM-dd'), 'MM/dd/yyyy') #"
},
...
References:
format-date-in-grid
jsfiddle
kendo ui date formatting
just need putting the datatype of the column in the datasource
dataSource: {
data: empModel.Value,
pageSize: 10,
schema: {
model: {
fields: {
DOJ: { type: "date" }
}
}
}
}
and then your statement column:
columns: [
{
field: "Name",
width: 90,
title: "Name"
},
{
field: "DOJ",
width: 90,
title: "DOJ",
type: "date",
format:"{0:MM-dd-yyyy}"
}
]
This is how you do it using ASP.NET:
add .Format("{0:dd/MM/yyyy HH:mm:ss}");
#(Html.Kendo().Grid<AlphaStatic.Domain.ViewModels.AttributeHistoryViewModel>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(c => c.AttributeName);
columns.Bound(c => c.UpdatedDate).Format("{0:dd/MM/yyyy HH:mm:ss}");
})
.HtmlAttributes(new { #class = ".big-grid" })
.Resizable(x => x.Columns(true))
.Sortable()
.Filterable()
.DataSource(dataSource => dataSource
.Ajax()
.Batch(true)
.ServerOperation(false)
.Model(model =>
{
model.Id(c => c.Id);
})
.Read(read => read.Action("Read_AttributeHistory", "Attribute", new { attributeId = attributeId })))
)
Try formatting the date in the kendo grid as:
columns.Bound(x => x.LastUpdateDate).ClientTemplate("#= kendo.toString(LastUpdateDate, \"MM/dd/yyyy hh:mm tt\") #");
The option I use is as follows:
columns.Bound(p => p.OrderDate).Format("{0:d}").ClientTemplate("#=formatDate(OrderDate)#");
function formatDate(OrderDate) {
var formatedOrderDate = kendo.format("{0:d}", OrderDate);
return formatedOrderDate;
}
As far as I'm aware in order to format a date value you have to handle it in parameterMap,
$('#listDiv').kendoGrid({
dataSource: {
type: 'json',
serverPaging: true,
pageSize: 10,
transport: {
read: {
url: '#Url.Action("_ListMy", "Placement")',
data: refreshGridParams,
type: 'POST'
},
parameterMap: function (options, operation) {
if (operation != "read") {
var d = new Date(options.StartDate);
options.StartDate = kendo.toString(new Date(d), "dd/MM/yyyy");
return options;
}
else { return options; }
}
},
schema: {
model: {
id: 'Id',
fields: {
Id: { type: 'number' },
StartDate: { type: 'date', format: 'dd/MM/yyyy' },
Area: { type: 'string' },
Length: { type: 'string' },
Display: { type: 'string' },
Status: { type: 'string' },
Edit: { type: 'string' }
}
},
data: "Data",
total: "Count"
}
},
scrollable: false,
columns:
[
{
field: 'StartDate',
title: 'Start Date',
format: '{0:dd/MM/yyyy}',
width: 100
},
If you follow the above example and just renames objects like 'StartDate' then it should work (ignore 'data: refreshGridParams,')
For further details check out below link or just search for kendo grid parameterMap ans see what others have done.
http://docs.kendoui.com/api/framework/datasource#configuration-transport.parameterMap
This might be helpful:
columns.Bound(date=> date.START_DATE).Title("Start Date").Format("{0:MM dd, yyyy}");