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
Related
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.
Anyone here can help me how to change the color of a needle in my speedometer chart? I copied this chart in Apache E-charts.
This is the script:
var dom = document.getElementById('performance-chart');
var myChart = echarts.init(dom, null, {
renderer: 'canvas',
useDirtyRect: false
});
var app = {};
var option;
option = {
series: [
{
type: 'gauge',
progress: {
show: true,
width: 18,
itemStyle: {
borderWidth: 10,
color: '#8D7CDB'
}
},
axisLine: {
lineStyle: {
width: 18
}
},
axisTick: {
show: false
},
splitLine: {
length: 5,
lineStyle: {
width: 1,
color: '#8D7CDB'
}
},
axisLabel: {
distance: 25,
color: '#8D7CDB',
fontSize: 9
},
anchor: {
show: true,
showAbove: true,
size: 25,
color: '#8D7CDB',
itemStyle: {
borderWidth: 8,
borderColor: '#8D7CDB'
}
},
title: {
show: false
},
detail: {
valueAnimation: true,
fontSize: 20,
color: '#8D7CDB',
formatter: "{value}%",
offsetCenter: [0, '70%']
},
data: [
{
value: 5.85
}
]
}
]
};
if (option && typeof option === 'object') {
myChart.setOption(option);
}
window.addEventListener('resize', myChart.resize);
The 'needle' is represented by the pointer parameter. Like most of echarts items, you can change the pointer style with itemStyle.
series: [
{
type: 'gauge',
... // the rest of the config
pointer: {
itemStyle: {
color: 'red'
}
},
},
]
Playing around with eCharts and i'm trying to replicate the graph shown in this tutorial
https://medium.com/#mailjontay/make-a-dynamic-chart-with-react-and-echarts-a-simple-tutorial-92a5c3c053a2
I'm using my own data sets, and both of my .js files are identical format to the ones used in the tutorial.
I'm having an issue with rendering the number of workers on my Yaxis, I'm not receiving any error messages and my data is defined.
My code is as follows:
import React, { Component } from "react";
import ReactEcharts from "echarts-for-react";
import { workForceDataFemale } from "./WorkForceDataFemale";
import { workForceDataMale } from "./WorkForceDataMale";
class App extends Component {
getOption = () => {
let sectors = [];
let years = [];
let workforceObject = [];
let workers = [];
Object.entries(workForceDataFemale).forEach(entry => {
years = [...years, entry[0]];
workforceObject = [...workforceObject, entry[1]];
entry[1].forEach(e => {
workers = [...new Set([...workers, e.n_workers])]
console.log(e.n_workers, "number of workers")
sectors = [...new Set([...sectors, e.sector])];
});
});
let options = years.map(year => {
let obj = {};
obj["series"] = [
{
stack: "group",
data: workForceDataFemale[year]
},
{
stack: "group",
data: workForceDataMale[year]
}
];
obj["title"] = {
text: `Number of workers over time by gender`
};
return obj;
});
return {
baseOption: {
timeline: {
autoPlay: false,
axisType: "category",
bottom: 20,
data: years,
height: null,
inverse: true,
left: null,
orient: "vertical",
playInterval: 1000,
right: 0,
top: 20,
width: 55,
label: {
normal: {
textStyle: {
color: "#aaa"
}
},
emphasis: {
textStyle: {
color: "#333"
}
}
},
symbol: "none",
lineStyle: {
color: "#aaa"
},
checkpointStyle: {
color: "#354EF6",
borderColor: "transparent",
borderWidth: 2
},
controlStyle: {
showNextBtn: false,
showPrevBtn: false,
normal: {
color: "#354EF6",
borderColor: "#354EF6"
},
emphasis: {
color: "#5d71f7",
borderColor: "#5d71f7"
}
}
},
color: ["#e91e63", "#354EF6"],
title: {
subtext: "Data from Sweet Analytics",
textAlign: "left",
left: "5%"
},
tooltip: { backgroundColor: "#555", borderWidth: 0, padding: 10 },
legend: {
data: ["Female", "Male"],
itemGap: 35,
itemHeight: 18,
right: "11%",
top: 20
},
calculable: true,
grid: {
top: 100,
bottom: 150,
tooltip: {
trigger: "axis",
axisPointer: {
type: "shadow",
label: {
show: true,
formatter: function(params) {
return params.value.replace("\n", "");
}
}
}
}
},
xAxis: [
{
axisLabel: {
interval: 0,
rotate: 55,
textStyle: {
baseline: "top",
color: "#333",
fontSize: 10,
fontWeight: "bold"
}
},
axisLine: { lineStyle: { color: "#aaa" }, show: true },
axisTick: { show: false },
data: sectors,
splitLine: { show: false },
type: "category"
}
],
yAxis: [
{
axisLabel: {
textStyle: { fontSize: 10 }
},
axisLine: { show: false },
axisTick: { show: false },
name: "Population",
splitLine: {
lineStyle: {
type: "dotted"
}
},
type: "value"
}
],
series: [{ name: "Female", type: "bar", data: workers }, { name: "Male", type: "bar", data: workers }]
},
options: options
};
};
render() {
return (
<ReactEcharts
option={this.getOption()}
style={{ height: "85vh", left: 50, top: 50, width: "90vw" }}
opts={{ renderer: "svg" }}
/>
);
}
}
export default App;
This is how far i've gotten :
And I'm trying to get to here:
In the series you should add stack you have in each object to add stack: "stackbar" like this :
series: [
{ name: "Female", type: "bar", data: workers, stack: "stackbar" },
{ name: "Male", type: "bar", data: workers , stack: "stackbar"}
]
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
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