How to create apexcharts (javascript) using json local file? - javascript

As the title say, I want to create apexchart using json data that I downloaded beforehand
I already search in internet to get json data use :
const df= require('data/processed.json');
And I already tried to call it df['liked'] as y and df['name'] as x
Is there something I miss?
Or call the column is not gonna do it?
I have also tried df.liked and df.name, btw
const df= require('data/processed.json');
var options = {
chart: {
height: 230,
type: 'line',
toolbar: {
show: false,
},
},
dataLabels: {
enabled: false
},
stroke: {
width: 2,
curve: 'smooth'
},
series: {
name: 'Liked',
data: df['liked']
},
legend: {
position: 'top',
},
xaxis: {
type: 'string',
data: df['name'],
axisBorder: {
show: false,
},
label: {
style: {
color: '#ccc'
}
},
},
yaxis: {
show: true,
// min: 10,
// max: 70,
labels: {
style: {
color: '#ccc'
}
}
},
colors: ['#73b4ff', '#59e0c5'],
fill: {
type: 'gradient',
gradient: {
shade: 'light',
gradientToColors: ['#4099ff', '#2ed8b6'],
shadeIntensity: 0.5,
type: 'horizontal',
opacityFrom: 1,
opacityTo: 1,
stops: [0, 100]
},
},
markers: {
size: 5,
colors: ['#4099ff', '#2ed8b6'],
opacity: 0.9,
strokeWidth: 2,
hover: {
size: 7,
}
},
grid: {
borderColor: '#cccccc3b',
}
}
var chart = new ApexCharts(document.querySelector("#unique-visitor-chart"), options);
chart.render();
enter code here

try to use :
const df = fetch("./data/processed.json")
.then(response => {
return response.json();
})
A documentation about fetch
This way will catch all data on your json and pu it in your const df by using the return :)
If you want to use require() look about : https://requirejs.org/
NOTE : Try to use a lot console.log() to debug your js app.

Related

Uncaught (in promise) TypeError: ser[i].data.map is not a function in apex chart.js

Getting the mentioned error when i try to render a apexchart chart from a json api
also the chart is not rendered in its div
console error
json api link
https://syed1ahmed.github.io/stage-gear/api.json
apex chart chart configs
var ChartOptions = {
series: [],
noData: {
text: 'Loading...'
},
chart: {
type: 'bar',
height: 300,
},
colors: 'blue',
plotOptions: {
bar: {
horizontal: !1,
dataLabels: {
position: 'top',
},
}
},
dataLabels: {
enabled: !1,
offsetX: -6,
style: {
fontSize: '12px',
colors: ['#fff']
}
},
stroke: {
show: true,
width: 1,
colors: ['#fff']
},
tooltip: {
shared: true,
intersect: false
},
yaxis: {
forceNiceScale: true,
labels: {
show: false,
}
},
grid: {
show: true,
borderColor: '#90A4AE',
strokeDashArray: 0.5,
position: 'back',
xaxis: {
lines: {
show: false
}
},
row: {
colors: 'red',
opacity: 0.2
},
},
xaxis: {
type : 'catagory',
labels: {
show: false,
rotate: 180,
}
}
};
var chart = new ApexCharts(document.querySelector("#chart"), ChartOptions);
chart.render();
const url = 'https://syed1ahmed.github.io/stage-gear/api.json';
$.getJSON(url, function (response) {
chart.updateSeries([{
name: 'monthly Volume In USD',
data: response
}])
});
code pen reproducing the problem faced
https://codepen.io/syed1ahmed/pen/eYrmzPO
can someone please solve this bug
Thanks
You can't just throw whole response to data, it has to be in a form apexcharts can understand. When you map data to array like this, chart will renders.
chart.updateSeries([{
name: 'monthly Volume In USD',
data: response.data.map((val) => val.volume)
}])
And if you want dates as categories updateOptions like this
chart.updateOptions({
series: [
{
name: "monthly Volume In USD",
data: response.data.map((val) => val.volume)
}
],
xaxis: {
categories: response.data.map((val) => val.date)
}
});

Insert variables from axios response into exported const

I am using axios in my vue.js project to do an HTTP POST and gather some variables for a vue-echart. I am trying to figure out the best way to do this and have somewhat hit a roadblock.
This is what is in my dashboard.vue file:
<script>
import { echartBar, echartPie } from "#/data/echarts";
import { echart1, echart2, echart3 } from "#/data/dashboard1";
export default {
metaInfo: {
title: "Dashboard v1"
},
mounted () {
axios
.post('https://testsite.com', 'Request data here')
.then(response => {
this.dataNeeded = response.data
console.log(info)
})
.catch(error => {
console.log(error)
this.errored = true
})
.finally(() => this.loading = false)
},
data() {
return {
echartBar,
echartPie,
echart1,
echart2,
echart3,
};
}
};
</script>
<style>
.echarts {
width: 100%;
height: 100%;
}
</style>
Then, here's the exported const from echarts.js:
var dark_heading = "#c2c6dc";
var chartLabels = ['Test1', 'Test2']
import { zoomBarData } from '#/data/echartSeries'
// start::echartBar
export const echartBar = {
legend: {
borderRadius: 0,
orient: 'horizontal',
x: 'right',
data: chartLabels
},
grid: {
left: '8px',
right: '8px',
bottom: '0',
containLabel: true
},
tooltip: {
show: true,
backgroundColor: 'rgba(0, 0, 0, .8)'
},
xAxis: [{
type: 'category',
data: dataNeeded.months,
axisTick: {
alignWithLabel: true,
},
splitLine: {
show: false
},
axisLabel: {
color: dark_heading,
},
axisLine: {
show:true,
color: dark_heading,
lineStyle: {
color: dark_heading,
}
}
}],
yAxis: [{
type: 'value',
axisLabel: {
color: dark_heading,
formatter: '${value}'
},
axisLine: {
show:false,
color: dark_heading,
lineStyle: {
color: dark_heading,
}
},
min: 0,
max: 100000,
interval: 25000,
splitLine: {
show: true,
interval: 'auto'
}
}],
series: [{
name: chartLabels[0],
data: dataNeeded.amounts,
label: { show: false, color: '#0168c1' },
type: 'bar',
barGap: 0,
color: '#bcbbdd',
smooth: true,
itemStyle: {
emphasis: {
shadowBlur: 10,
shadowOffsetX: 0,
shadowOffsetY: -2,
shadowColor: 'rgba(0, 0, 0, 0.3)'
}
}
},
{
name: chartLabels[1],
data: dataNeeded.amounts2,
label: { show: false, color: '#639' },
type: 'bar',
color: '#7569b3',
smooth: true,
itemStyle: {
emphasis: {
shadowBlur: 10,
shadowOffsetX: 0,
shadowOffsetY: -2,
shadowColor: 'rgba(0, 0, 0, 0.3)'
}
}
}
]
}
Basically, if I'd like to use data coming back from the axios request (JSON) in place of the data listed in echarts.js (being an exported const), what would be my best option?
The const is basically returning a plain object. Axios will receive the object data, which you can simply access or assign its values to other objects.
In your case, you may assign a value to the echartBar object in the scope of your component like so:
this.echartBar.xAxis[0].data = response.data.months
This assumes you have a months property in your response data.
This process can be cumbersome especially when you have a lot of properties on the echartBar object like you have. You'll need to check for arrays in arrays etc. Libraries like lodash might be helpfull in that case, for example its set function: https://lodash.com/docs/4.17.15#set

Highcharts angular wrapper labels.items don't refresh

I'm using angular6 and the office highcharts angular wrapper (https://github.com/highcharts/highcharts-angular) in version 2.4.0.
Everything is working good except the labels that can be placed manually on the chart.
I just don't manage to get them refreshed.
I have a graph that can be filtered through the back-end. When I get the new generated data I update the data in my chartOptions which are used in the html as [options]="chartOptions" for the angular component.
The chartOptions are instanciated from my default class like this: this.chartOptions = new GraphConfigSeqAtteptedVsAchived().chartOptions;
The Class looks like this:
`import * as Highcharts from 'highcharts';
export class GraphConfigSeqAtteptedVsAchived{
public chartOptions: any;
constructor(){
this.chartOptions = {
chart: {
height: 600,
width: 620,
events:{load: function(){
this.myTooltip = new Highcharts.Tooltip(this, this.options.tooltip);
}
},
backgroundColor: 'transparent',
},
credits: {
text: 'charname',
href: ''
},
labels: {
},
exporting:{
chartOptions:{
title: {
text:'not set',
style:{
color: '#000000'
},
margin: 0
}
}
},
tooltip: {
enabled: false
},
xAxis: {
min: -10,
max: 0,
width: 535,
title: {
text: 'Rainfall (mm)',
style: {
fontWeight: "bold",
color: '#000000'
}
},
reversed: true,
tickInterval: 1
},
yAxis: {
min: -10,
max: 0,
title: {
text: 'Rainfall (mm)',
style: {
fontWeight: "bold",
color: '#000000'
}
},
reversed: true,
tickInterval: 1
},
title: {
text: ' as',
margin: 0,
style:{
color: 'transparent'
}
},
legend: {
layout: 'vertical',
align: 'left',
verticalAlign: 'top',
x: 100,
y: 90,
floating: true,
backgroundColor: '#FFFFFF',
borderWidth: 1,
navigation: {
enabled: false
}
},
plotOptions: {
scatter: {
stickyTracking: false,
allowPointSelect: true,
marker: {
radius: 3,
states: {
hover: {
enabled: true,
lineColor: 'rgb(100,100,100)'
}
}
},
tooltip: {
headerFormat: '<b>{series.name}</b><br>',
pointFormat: '',
hideDelay: 500
},
symbol: "circle",
events: {
mouseOut: function() {
this.chart.myTooltip.hide();
this.chart.myTooltip.options.enabled = false;
},
mouseOver: function() {
if(this.halo) {
this.halo.attr({
'class': 'highcharts-tracker'
}).toFront();
}
},
click: function(event) {
this.chart.myTooltip.options.enabled = true;
this.chart.myTooltip.refresh(event.point, event);
}
}
},
line:{
events: {
legendItemClick: function () {
return false;
}
}
},
series:{
allowPointSelect: true
}
},
series: [{
type: 'line',
data: [[30, 30], [-30, -30]],
marker: {
enabled: false
},
states: {
hover: {
lineWidth: 1
}
},
showInLegend: false,
color: "rgba(0, 0, 0, 0.6)",
enableMouseTracking: false
},{
type: 'line',
data: [[30, 29.5], [-29.5, -30]],
marker: {
enabled: false
},
states: {
hover: {
lineWidth: 0
}
},
showInLegend: false,
dashStyle: 'ShortDash',
color: "rgba(125, 162, 159, 0.35)",
enableMouseTracking: false
},{
type: 'line',
data: [[29.5, 30], [-30, -29.5]],
marker: {
enabled: false
},
states: {
hover: {
lineWidth: 0
}
},
showInLegend: false,
dashStyle: 'ShortDash',
color: "rgba(125, 162, 159, 0.35)",
enableMouseTracking: false
},{
type: 'line',
data: [[29, 30], [-30, -29]],
marker: {
enabled: false
},
states: {
hover: {
lineWidth: 0
}
},
showInLegend: false,
dashStyle: 'ShortDash',
color: "rgba(197, 144, 161, 0.35)",
enableMouseTracking: false
},{
type: 'line',
data: [[30, 29], [-29, -30]],
marker: {
enabled: false
},
states: {
hover: {
lineWidth: 0
}
},
showInLegend: false,
dashStyle: 'ShortDash',
color: "rgba(197, 144, 161, 0.35)",
enableMouseTracking: false
}]
}
}
}`
The generated data is in the typescript dynamically added and all of that works just fine. Everything is refreshed after I set the updateFlag for [(update)]="updateGraph". The axis titles are also fine.
The only thing that's not refreshed for me are the labels i dynamically added to the chart like this:
let labelTotalNumberOfEyes = {
html : this.translate.instant('GRAPHS.TOTAL_NUMBER_OF_EYES') + ': ' + (scatterSeries.data.length + scatterSeriesRetreatment.data.length),
style : {
left : '330px',
top : '368px',
fontSize : '14px',
backgroundColor: '#FFFFFF',
borderWidth: 1,
}
}
this.chartOptions.labels.items.push(labelTotalNumberOfEyes);
Does someone have any idea what I'm might doing wrong? I don't see any further option than just setting this update flag and it works fine for everything but the labels.
Please let me know if you're missing any information.
Thanks in advance.
This issue is actually a Highcharts bug. I've reported it here: https://github.com/highcharts/highcharts/issues/10429.
As a workaround, you can use Highcharts.SVGRenderer to add a custom label and store reference to it in your component. Next, when updating, call attr() method on the label (Highcharts.SVGElement) and set new options. Check demo and code posted below.
Add a label on chart callback:
constructor() {
const self = this;
this.chartCallback = chart => {
self.chart = chart;
self.label = chart.renderer
.text("test", 100, 100)
.css({
fill: "#555",
fontSize: 16
})
.add()
.toFront();
};
}
call attr() on the label while updating:
update_chart() {
const self = this,
chart = this.chart;
chart.showLoading();
setTimeout(() => {
chart.hideLoading();
self.chartOptions.series = [
{
data: [10, 25, 15],
name: "updatedSerieName"
}
];
self.chartOptions.yAxis.title.text = "updatedData";
self.label
.attr({
text: "test1",
x: 150,
y: 120
})
.css({
fill: "red",
fontSize: 20
});
self.updateFromInput = true;
}, 2000);
}
Demo:
https://codesandbox.io/s/8zo0yvqqwj
API reference:
https://api.highcharts.com/class-reference/Highcharts.SVGRenderer#text
https://api.highcharts.com/class-reference/Highcharts.SVGElement#attr

Echart icon in series tooltip

So i have the following configuration:
const frequencyChartoption = {
title: {},
tooltip: {},
legend: {
data: ['Frekvens', 'Vigtighed']
},
xAxis: {
type: 'category',
data: ['marker_01', 'marker_02'],
axisLabel: {
formatter: function (value) {
return '{' + value + '| }\n{value|}';
},
margin: 20,
rich: {
value: {
lineHeight: 30,
align: 'center'
},
marker_01: {
height: 20,
align: 'center',
backgroundColor: {
image: icons.marker_01
}
},
marker_02: {
height: 20,
align: 'center',
backgroundColor: {
image: icons.maker_02
}
},
}
}
},
yAxis: {},
series: [{
name: 'Frekvens',
type: 'bar',
data: frequencyChartFrequencyScore,
tooltip: icons.marker_01,
itemStyle: {
normal: {
color: colors[0],
label: {
interval: 5,
show: true,
position: 'top',
formatter: '\n{c}'
}
}
}
},
{
name: 'Vigtighed',
type: 'bar',
data: frequencyChartImportance,
itemStyle: {
normal: {
color: colors[1],
label: {
show: true,
position: 'top',
formatter: '\n{c}'
}
}
}
}
]
};
Now as you can see i am using two images as my xAxis
Now i wish to make these show up on my tooltip when i hover over the chart. However i am not quite sure how to do that and was hoping some of you might be able to help?
Simply stated, a series may have a tooltip but the tooltip must be listed as an object with an identifying trigger (see tooltip documentation).
series: [{
name: 'Frekvens',
type: 'bar',
data: frequencyChartFrequencyScore,
tooltip: {
show: true,
trigger: 'axis',
formatter: (params) => {
// see tooltip.formatter for details
// you want to focus on the 'marker' property
return params[0].name;
}
}
}]
With this in mind, you can set two variables and print them as need be within the output of your tooltip. See the additional example below (from CodePen).
var myChart = echarts.init(document.getElementById("main"));
// specify chart configuration item and data
var option = {
title: {
text: "ECharts entry example"
},
tooltip: {
show: true,
trigger: "axis",
backgroundColor: 'rgba(0, 0, 0, 0.8)',
formatter: (params) => {
// create new marker
var icon0 = `<span data-tooltip="minimum" style="border-left: 2px solid #fff;display: inline-block;height: 12px;margin-right: 5px;width: 20px;"><span style="background-color:${params[0].color};display: block;height: 4px;margin-top: 4px;width: 20px;"></span></span>`;
var icon1 = `<span data-tooltip="implied-high" style="background-color:rgba(255,255,255,.75);border-radius: 2px;display: inline-block;height: 12px;margin-right:5px;width: 20px;"><span style="background-color:${params[0].color};border: 1px solid ${params[0].color};border-radius:50%;display:block;height:6px;margin-left:7px;margin-top:3px;width:6px;"></span></span>`;
console.log("params", params, params[0].name);
return `${icon0} ${params[0].name}
${icon1} ${params[0].value}`;
},
textStyle: {
fontWeight: 'bold',
fontSize: 18
}
},
legend: {
data: ["Sales"]
},
xAxis: {
data: ["shirt", "cardign", "chiffon shirt", "pants", "heels", "socks"]
},
yAxis: {},
series: [
{
name: "Sales",
type: "bar",
data: [5, 20, 36, 10, 10, 20]
}
]
};
// use configuration item and data specified to show chart
myChart.setOption(option);

Add Values to data under series dynamically - echarts

I have created a Bar graph using echarts. I want to bind multiple values to data object dynamically, currently I'm able to bind only single value. here is my java script. I'mm a newbie for this, hoping for a fully functional solution.
var myChart = echarts.init(document.getElementById('page_views_today'));
var option = {
// Setup grid
grid: {
zlevel: 0,
x: 20,
x2: 40,
y: 20,
y2: 20,
borderWidth: 0,
backgroundColor: 'rgba(0,0,0,0)',
borderColor: 'rgba(0,0,0,0)',
},
// Add tooltip
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'shadow', // line|shadow
lineStyle: { color: 'rgba(0,0,0,.5)', width: 1 },
shadowStyle: { color: 'rgba(0,0,0,.1)' }
}
},
// Add legend
legend: {
data: []
},
toolbox: {
orient: 'vertical',
show: true,
showTitle: true,
color: ['#bdbdbd', '#bdbdbd', '#bdbdbd', '#bdbdbd'],
feature: {
mark: { show: false },
dataZoom: {
show: true,
title: {
dataZoom: 'Data Zoom',
dataZoomReset: 'Reset Zoom'
}
},
dataView: { show: false, readOnly: true },
magicType: {
show: true,
itemSize: 12,
itemGap: 12,
title: {
line: 'Line',
bar: 'Bar',
},
type: ['line', 'bar'],
option: {
/*line: {
itemStyle: {
normal: {
color:'rgba(3,1,1,1.0)',
}
},
data: [1,2,3,4,5,6,7,8,9,10,11,12]
}*/
}
},
restore: { show: false },
saveAsImage: { show: true, title: 'Save as Image' }
}
},
// Enable drag recalculate
calculable: true,
// Horizontal axis
xAxis: [{
type: 'category',
boundaryGap: false,
data: [
'0h-2h', '2h-4h', '4h-6h', '6h-8h', '8h-10h', '10h-12h', '12h-14h', '14h-16h', '16h-18h', '18h-20h', '20h-22h', '22h-24h'
],
axisLine: {
show: true,
onZero: true,
lineStyle: {
color: 'rgba(63,81,181,1.0)',
type: 'solid',
width: '2',
shadowColor: 'rgba(0,0,0,0)',
shadowBlur: 5,
shadowOffsetX: 3,
shadowOffsetY: 3,
},
},
axisTick: {
show: false,
},
splitLine: {
show: false,
lineStyle: {
color: '#fff',
type: 'solid',
width: 0,
shadowColor: 'rgba(0,0,0,0)',
},
},
}],
// Vertical axis
yAxis: [{
type: 'value',
splitLine: {
show: false,
lineStyle: {
color: 'fff',
type: 'solid',
width: 0,
shadowColor: 'rgba(0,0,0,0)',
},
},
axisLabel: {
show: false,
},
axisTick: {
show: false,
},
axisLine: {
show: false,
onZero: true,
lineStyle: {
color: '#ff0000',
type: 'solid',
width: '0',
shadowColor: 'rgba(0,0,0,0)',
shadowBlur: 5,
shadowOffsetX: 3,
shadowOffsetY: 3,
},
},
}],
// Add series
series: [
{
name: 'Page Views',
type: 'bar',
smooth: true,
symbol: 'none',
symbolSize: 2,
showAllSymbol: true,
barWidth: 10,
itemStyle: {
normal: {
color: 'rgba(63,81,181,1.0)',
borderWidth: 2, borderColor: 'rgba(63,81,181,1)',
areaStyle: { color: 'rgba(63,81,181,1)', type: 'default' }
}
},
data: []
}
]
};
Here is my java-script function from where I want to bind the values dynamically.
// Load data into the ECharts instance
load_graph_with_positions(option);
function load_graph_with_positions(option) {
option.series[0].data[0] = 1234;
myChart.setOption(option);
}
One way to do this is by passing values in an array and then shifting the previous values, while pushing-in the data. Following is the example of shiting and pushing the data:
option.series[0].data.shift();
option.series[0].data.push(json.num);
Hence your function will become:
function load_graph_with_positions(option,values) {
var valuesLength = values.length;
for (var i = 0; i < valuesLength; i++) {
option.series[0].data.shift();
option.series[0].data.push(values[i]);
}
myChart.setOption(option);
}
You can also refer to following github example for dynamic addition:
https://github.com/hisune/Echarts-PHP/blob/master/demo/dynamic.php

Categories

Resources