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"}
]
Related
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'
}
},
},
]
I want to show the total value and x axis label on top of my stacked bar chart so it look like this
but right now, i'm only can show the total value, i don't know how to add the x axis label, so far mine look like this
i'm also want to custom my tooltip to look like this
Here's my code:
export default {
name: 'BarAllYear',
data() {
return {
BarAllYearData,
};
},
mounted() {
const ctx = document.getElementById('bar-all-year').getContext('2d');
const BarChart = {
type: 'bar',
data: this.BarAllYearData,
plugins: [ChartDataLabels],
options: {
borderWidth: 1,
responsive: true,
plugins: {
legend: {
display: false,
},
tooltip: {
xAlign: 'center',
yAlign: 'bottom',
backgroundColor: '#FFF',
displayColors: false,
titleFont: {
size: 20,
},
bodyFont: {
size: 18,
},
titleColor(tooltipItem) {
const titleLabelColor = tooltipItem.tooltip.labelColors[0].backgroundColor;
return titleLabelColor;
},
bodyColor() {},
},
datalabels: {
color: '#666666',
align: 'top',
anchor: 'end',
offset: 1,
formatter(value, context) {
const sumValue = context.chart.config.data.datasets.map((datapoint) => datapoint.data[context.dataIndex]);
function totalSum(total, datapoint) {
return total + datapoint;
}
const sum = sumValue.reduce(totalSum, 0);
return `${sum}`;
},
font: {
weight: 'bold',
size: 16,
},
},
},
scales: {
x: {
ticks: {
color: 'black',
font: {
weight: 'bold',
size: 16,
},
},
stacked: true,
},
y: {
ticks: {
stepSize: 1,
font: {
size: 18,
},
},
stacked: true,
},
},
layout: {
padding: 20,
},
},
};
/* eslint-disable no-new */
new Chart(ctx, BarChart);
},
};
and this is the BarAllYearData:
const DonutAllYearData = {
labels: [
'Butuh Perhatian Khusus',
'Dalam Proses',
'Selesai',
],
datasets: [{
label: 'My First Dataset',
data: [16, 3, 5],
backgroundColor: [
'#FF7A00',
'#23C4DB',
'#666666',
],
hoverOffset: 4,
}],
};
export default DonutAllYearData;
I'm using vue 3 by the way.
Anyway, thanks for the help
I am trying to get both lines on my chart to scale correctly, I have read through the documentation but can't seem to find how to do this.
images
The above image shows what happens to the orange line when a secondary axis is added. It's like they are using the same scale rather than their own.
I currently have the below code:
$(function(e) {
/*-----echart1-----*/
var options = {
chart: {
height: 300,
type: "line",
stacked: false,
toolbar: {
enabled: false
},
dropShadow: {
enabled: true,
opacity: 0.1,
},
},
colors: ["#f99433", '#6759C8'],
dataLabels: {
enabled: false
},
stroke: {
curve: "straight",
width: [3, 3, 0],
dashArray: [0, 4],
lineCap: "round"
},
grid: {
padding: {
left: 0,
right: 0
},
strokeDashArray: 3
},
markers: {
size: 0,
hover: {
size: 0
}
},
series: [{
name: "Price",
type: 'line',
data: ["4.12","4.08","3.98","3.99","3.95","4.01"] }, {
name: "Socials",
type: 'line',
data: ["23","17","6","6","7","7"] }],
yaxis: [
{
title: {
text: "Price",
},
},
{
opposite: true,
title: {
text: "Socials"
}
}
],
xaxis: {
type: "month",
categories: ["2021-12-09 17:01:25","2021-12-09 18:01:29","2021-12-09 19:01:33","2021-12-09 20:01:37","2021-12-09 21:01:42","2021-12-09 22:01:45"],
axisBorder: {
show: false,
color: 'rgba(119, 119, 142, 0.08)',
},
labels: {
style: {
color: '#8492a6',
fontSize: '12px',
},
},
},
fill: {
gradient: {
inverseColors: false,
shade: 'light',
type: "vertical",
opacityFrom: 0.85,
opacityTo: 0.55
}
},
tooltip: {
show:false
},
legend: {
position: "top",
show:true
}
}
var chart = new ApexCharts(document.querySelector("#chartArea"), options);
chart.render();
In version 3, you can use the function and event of the echarts themselves directly, overriding the function for the event, as written const updateAxisPointer = function(event)... I can’t understand how to do this in version 4. Here is a [link][1] to version 4. I tried to work with the delegateMethod function, but it displays the error this.chart [methodName] is not a function.
const updateAxisPointer = function(event) {
console.log('event', event);
};
this.$refs.eChart.delegateGet('updateAxisPointer', updateAxisPointer);
Here is how the code looks for version 3
<div class="echarts">
<IEcharts :option="option" #ready="onReady" />
</div>
</template>
<script>
import IEcharts from 'vue-echarts-v3/src/full.js';
export default {
name: 'View',
components: {
IEcharts,
},
data() {
// const that = this
return {
ins: null,
echarts: null,
option: {
legend: {
orient: 'vertical',
top: 40,
left: 60,
},
tooltip: {
trigger: 'axis',
showContent: false,
},
dataset: {
source: [],
},
yAxis: {
type: 'value',
name: '',
nameLocation: 'middle',
nameGap: 40,
},
grid: {
left: 40,
right: 37,
bottom: 45,
top: '50%',
containLabel: true,
},
series: [],
}
};
},
methods: {
onReady(instance, echarts) {
const that = this;
that.ins = instance;
that.echarts = echarts;
const updateAxisPointer = function(event) {
let xAxisInfo = event.axesInfo[0];
if (xAxisInfo) {
let dimension = xAxisInfo.value + 1;
that.ins.setOption({
series: {
id: 'pie',
label: {
formatter: '{b}: {#[' + dimension + ']} ({d}%)',
},
encode: {
value: dimension,
tooltip: dimension,
},
},
});
}
};
that.ins.on('updateAxisPointer', updateAxisPointer);
},
},
};
</script>```
[1]: https://github.com/ecomfe/vue-echarts/blob/master/src/components/ECharts.vue
You can use #updateAxisPointer directly with Vue's event handling.
I tested the following example with vue-echarts-v5.0 but it should already work in version 4.1.
App.vue:
<template>
<chart
:options="options"
#updateAxisPointer="updateAxisPointer"
>
</chart>
</template>
<script>
import ECharts from 'vue-echarts'
export default {
name: 'Interactive',
components: {
'chart': ECharts,
},
data() {
return {
options: {
title: {
text: 'Interactive example chart',
left: 'center',
textStyle: {
color: '#000'
}
},
tooltip: {
trigger: 'axis',
showContent: false
},
dataset: {
source: [
['technology', '2012', '2013', '2014', '2015', '2016', '2017'],
['photovoltaic', 41.1, 30.4, 65.1, 53.3, 83.8, 98.7],
['wind', 86.5, 92.1, 85.7, 83.1, 73.4, 55.1],
['natural gas', 24.1, 67.2, 79.5, 86.4, 65.2, 82.5],
['coal', 55.2, 67.1, 69.2, 72.4, 53.9, 39.1],
['oil', 50.2, 60, 60.2, 70.4, 50.9, 39.1],
['battery', 20, 30, 80.2, 50.4, 10.9, 29.1],
['hidrogen', 30, 40, 60, 50, 50, 19.1]
]
},
xAxis: {type: 'category'},
yAxis: {gridIndex: 0},
grid: {top: '55%'},
series: [
{type: 'line', smooth: true, seriesLayoutBy: 'row'},
{type: 'line', smooth: true, seriesLayoutBy: 'row'},
{type: 'line', smooth: true, seriesLayoutBy: 'row'},
{type: 'line', smooth: true, seriesLayoutBy: 'row'},
{type: 'line', smooth: true, seriesLayoutBy: 'row'},
{type: 'line', smooth: true, seriesLayoutBy: 'row'},
{type: 'line', smooth: true, seriesLayoutBy: 'row'},
{
type: 'pie',
id: 'pie',
radius: '30%',
center: ['50%', '30%'],
label: {
formatter: '{b}: {#2012} ({d}%)'
},
encode: {
itemName: 'technology',
value: '2012',
tooltip: '2012'
}
}
]
}
};
},
methods: {
updateAxisPointer(params) {
var xAxisInfo = params.axesInfo[0];
if (xAxisInfo) {
var dimension = xAxisInfo.value + 1;
this.options.series = [{
id: 'pie',
label: {
formatter: '{b}: {#'+dimension+'} ({d}%)'
},
encode: {
value: dimension,
tooltip: dimension
}
}]
}
},
},
};
</script>
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);