Create the Mixed Chart in react - reactjs

I want to create the chart mixed chart with line and bar like the below image.

You firstly, import line from the chartjs-2 library. After add two dataset, and indicate one of them is bar chart. type:'bar' .
if you want to add two sides titles, you have to add yAxisID on the datasets. After this, you can put y and y1 axis on the options inside of the scales. Then add titles name in there. Please examine the codes.
Check the result of code:
import React from 'react'
import { Line } from "react-chartjs-2";
function MainChart() {
return (
<>
<Line
data={{
labels: ["1","2", "3", "4", "5"],
datasets: [
{
label: "Line value",
data: [1,2,3,4,5],
borderColor: `rgba(255,200,100, 0.1)`,
backgroundColor: `rgba(255,200,100,0.5)`,
yAxisID: 'y',
},
{
type: 'bar',
label: "bar value",
data: [1,2,3,4,5],
yAxisID: 'y1',
borderColor:"rgb(120, 80, 0, 0.8)",
backgroundColor: "rgb(50, 216, 190, 0.3)",
}
],
}}
options={{
scales: {
y: {
type: 'linear',
display: true,
position: 'left',
ticks: {
color: "rgba(0, 0, 0, 1)",
},
grid: {
drawBorder: true,
drawTicks: true,
color: "rgba(0, 0, 0, 0.2)",
},
title: {
display: true,
text: "Line Title",
font: {
size: 17
},
},
},
y1: {
type: 'linear',
display: true,
position: 'right',
title: {
display: true,
text: "Bar Title",
font: {
size: 15
},
},
},
},
}}
/>
</>
)
}
export default MainChart

USE APEXCHARTS. I tried literally everything and apexcharts was the easiest of all the charts for reactjs. LMK if you have anymore questions!
https://apexcharts.com/react-chart-demos/mixed-charts/line-column/#
NOTE: the doc doesn't mention it but you want to import ReactApexCharts from the library like below.
you're gonna need to convert the class states into functional component states in react which shouldn't be too hard if you know basic React. Here's what your inside code should similarly look like:
import React, { useState } from "react";
import ReactApexChart from "react-apexcharts";
export default function Graph(props) {
const [options, setOptions] = useState({
chart: {
height: 350,
type: "line",
},
stroke: {
width: [0, 4],
},
dataLabels: {
enabled: true,
enabledOnSeries: [1],
},
labels: ['Label 1', 'Label 2', 'Label 3', 'Label 4', 'Label 5'],
// xaxis: { DONT NEED THIS, but if you check out the docs they have some useful stuff.
// type: 'datetime'
// },
yaxis: [
{
title: {
text: "Total Number of Sessions",
},
},
{
opposite: true,
title: {
text: "Total Traffic (Gbps)",
},
},
],
});
const [series, setSeries] = useState([
{
name: "Total Number of Sessions",
type: "column",
data: [440, 505, 414, 671, 227]//your data goes here
},
{
name: "Total Traffic (Gbps)",
type: "line",
data: [40, 50, 41, 67, 22]//your data goes here
},
]);
return (
<>
<ReactApexChart
options={options}
series={series}
type='line'
height={350}
/>
</>
);
}

Related

how to use dimension values in markpoints

I am using react-Echart for drawing some charts.
but I stucked some problems.
From what I read in the document, If I set proper dimension in series props, I can also use value of that dimensions in labels using formatter props.
However, even if I try many times, the formatter doesn't work properly.
Attached is the option data I used. Please check it out and give me an answer.
const option:EChartsOption = {
title: {
show: false
},
xAxis: {
show: false,
type: 'time'
},
yAxis: {
type: 'value',
position: 'right'
},
// ...
dataset:
{
dimensions: [
'date', 'randomV', 'dailyIncome', 'dailyOutcome', 'percent'
],
source: fakeLineGraphData // [{date:string, randomV:number, dailyIncome: number, dailyOutcome:number , percent: number}]
},
series: [{
dimensions: ['date', 'randomV'],
type: 'line',
symbol: 'none',
showSymbol: false,
markPoint: {
itemStyle: {
color: '#74d527'
},
data: [
{
type: 'max',
name: 'Max',
symbol: 'triangle',
symbolSize: 10,
symbolRotate: 180,
symbolOffset: [0, -20],
label: {
position: 'right',
formatter: `max {c} ({#percent}%)`, // don't works!
color: 'gray'
}
},
{
type: 'min',
name: 'Min',
symbol: 'triangle',
symbolSize: 10,
symbolOffset: [0, 20],
label: {
position: 'right',
formatter: `최저 {c} (-${#percent}%)`, // don't works!
color: 'gray'
}
}
]
},
//...
]
};
Doc which I refered : https://echarts.apache.org/en/option.html#series-line.markPoint.label.formatter

Echarts 3.6.2 Legend Type "scroll" does not be applied correctly

In my angularJs project,I have a pie Echarts and I define it like below.The problem is that I may have lots of legend and I see I can use type:'scroll' to make it from here, but I failed and it has no impact.
$scope.pieEcharts1 = {
option: {
title: {
text: 'MyPieChart',
left: 'left',
},
tooltip: {
trigger: 'item',
formatter: "{a} <br/>{b} : {c} ({d}%)"
},
legend: {
orient: 'vertical',
left: 'right',
type:'scroll',//does not work
data: []
},
label: {
normal: {
show: true,
formatter: '{d}%'
}
},
labelLine: {
normal: {
show: true
}
},
series: [{
name: 'MyData',
type: 'pie',
radius: '62%',
center: ['50%', '50%'],
data: [],
itemStyle: {
emphasis: {
shadowBlur: 10,
shadowOffsetX: 0,
shadowColor: 'rgba(0, 0, 0, 0.5)'
}
}
}]
}
}
}
//http request to get data
$scope.pieEcharts1.option.legend.data = nameArray
$scope.pieEcharts1.option.series[0] = dataArray
What is the problem in my code?
The scrollable legned is supported from v3.7.0.
https://echarts.apache.org/zh/changelog.html#v3-7-0

Issue with chartjs linear gradient for the mixed bar chart in ReactJS is not calculated for each individual Bars

Our requirement is to render the bar chart as Expected Image. we are using chartJs library to render the chart. we are able to render the bar chart but for one of the bar we need to show
the background color as gradient. To achieve this we used the following below code snippet:
but it render as Rendered graph. Can you please help me out in rendering the chart as expected.
JSFiddleLink
const data = [{
type: "Sample 1",
data: [600, 400, 200, 800]
}, {
type: "Sampel 2",
data: [700, 300, 600, 600]
}, {
type: "Total",
data: [1300, 700, 800, 1400]
}];
const gradient = document.getElementById('myChart').getContext('2d').createLinearGradient(0, 250, 0, 0);
gradient.addColorStop(1, '#acd7fa')
gradient.addColorStop(0.4, '#FFFFFF')
new Chart('myChart', {
type: "bar",
data: {
labels: ["A", "B", "C", "D"],
datasets: [
{
label: data[0].type,
xAxisID: "x1",
data: data[0].data,
// fillColor: background_1,
// highlightFill: background_2,
backgroundColor: "rgb(54, 162, 235)" ,
// backgroundColor: background_1,
barPercentage: 1,
},
{
label: data[1].type,
xAxisID: "x1",
data: data[1].data,
backgroundColor:"rgb(255, 159, 64)",
barPercentage: 1,
},
{
label: data[2].type,
xAxisID: "x2",
data: data[2].data,
backgroundColor: gradient,
barPercentage: 1,
},
],
},
options: {
legend: {
labels: {
filter: item => item.text != 'Total'
}
},
scales: {
yAxes: [{
ticks: {
min: 0,
stepSize: 200
}
}],
xAxes: [{
id: 'x1'
},
{
id: 'x2',
display: false,
offset: true
}
]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<canvas id="myChart" height="150"></canvas>
The Plugin Core API offers a range of hooks that may be used for performing custom code. You can use the afterLayout hook for creating different gradients for each value of the third dataset (the totals).
Please take a look at your amended code below and see how it works. You may also consult this StackBlitz that illustrates how it can be done with react-chartjs-2.
const data = [
{ type: "Sample 1", data: [600, 400, 200, 800] },
{ type: "Sampel 2", data: [700, 300, 600, 600] },
{ type: "Total", data: [1300, 700, 800, 1400] }
];
new Chart('myChart', {
type: "bar",
plugins: [{
afterLayout: chart => {
let ctx = chart.chart.ctx;
ctx.save();
let yAxis = chart.scales["y-axis-0"];
let yBottom = yAxis.getPixelForValue(0);
let dataset = chart.data.datasets[2];
dataset.backgroundColor = dataset.data.map(v => {
let yTop = yAxis.getPixelForValue(v);
let gradient = ctx.createLinearGradient(0, yBottom, 0, yTop);
gradient.addColorStop(0.4, '#FFFFFF');
gradient.addColorStop(1, '#acd7fa');
return gradient;
});
ctx.restore();
}
}],
data: {
labels: ["A", "B", "C", "D"],
datasets: [{
label: data[0].type,
xAxisID: "x1",
data: data[0].data,
backgroundColor: "rgb(54, 162, 235)",
barPercentage: 1
},
{
label: data[1].type,
xAxisID: "x1",
data: data[1].data,
backgroundColor: "rgb(255, 159, 64)",
barPercentage: 1
},
{
label: data[2].type,
xAxisID: "x2",
data: data[2].data,
barPercentage: 1
}
]
},
options: {
legend: {
labels: {
filter: item => item.text != 'Total'
}
},
scales: {
yAxes: [{
ticks: {
min: 0,
stepSize: 200
}
}],
xAxes: [{
id: 'x1'
},
{
id: 'x2',
display: false,
offset: true
}
]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<canvas id="myChart" height="150"></canvas>

Creating mixed Bar Chart with ReactJS using recharts or react-chartjs-2

image screen shot I am trying to implement multiple Bar chart for the below requirement of chart in ReactJS using recharts or react-chartjs-2 library.
I was unable to find any direct solution available. Any suggestions how to create a similar type of chart
const data = [ { type: "Sample 1", data: [600, 400, 200, 800] }, { type: "Sampel 2", data: [700, 300, 600, 600] }, { type: "Total", data: [1300, 700, 800, 1400] } ];
The main requirement can be met by defining two xAxes, one for the individual values ('x1'), the other one for the total bar ('x2').
For further details, please consult the chapter "Creating Multiple Axes" from Chart.js documentation
Please take a look at below code sample and see how it works. While this is a pure JavaScript solution, the concept should also work for react-chartjs-2.
const data = [{
type: "Sample 1",
data: [600, 400, 200, 800]
}, {
type: "Sampel 2",
data: [700, 300, 600, 600]
}, {
type: "Total",
data: [1300, 700, 800, 1400]
}];
new Chart('myChart', {
type: "bar",
data: {
labels: ["A", "B", "C", "D"],
datasets: [{
label: data[0].type,
xAxisID: 'x1',
data: data[0].data,
backgroundColor: 'rgb(54, 162, 235)',
barPercentage: 1
},
{
label: data[1].type,
xAxisID: 'x1',
data: data[1].data,
backgroundColor: 'rgb(255, 159, 64)',
barPercentage: 1
},
{
label: data[2].type,
xAxisID: 'x2',
data: data[2].data,
backgroundColor: 'rgb(172, 215, 250)',
barPercentage: 1
}
]
},
options: {
legend: {
labels: {
filter: item => item.text != 'Total'
}
},
scales: {
yAxes: [{
ticks: {
min: 0,
stepSize: 200
}
}],
xAxes: [{
id: 'x1'
},
{
id: 'x2',
display: false,
offset: true
}
]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<canvas id="myChart" height="90"></canvas>

Chartjs: Draw chart with only yAxis zero tick

Hell, all,
I would like to draw the chart like this:
Currently, I can use afterBuildTicks to get only zero yAxis. But the problem is that the whole other ticks were removed also. So Not sure if we have a way to draw zero tick and keep other ticks hidden except the label.
var ctx = document.getElementById("myChart").getContext("2d");
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: ['Value 1', 'Value 2', 'Value 3', 'Value 4'],
datasets: [{
label: "Dataset",
data: [20, 15, 27, 18],
backgroundColor: 'rgba(54, 162, 235,0.5)',
}],
},
options: {
responsive: true,
elements: {
line: {
fill: false
}
},
scales: {
xAxes: [
{
position: 'top',
display: true,
gridLines: {
display: true,
},
stacked: true,
ticks: {
fontColor: "#C4C4C4",
fontSize: 10,
}
}
],
yAxes: [
{
type: 'linear',
display: true,
position: 'right',
id: 'y-axis-1',
gridLines: {
display: true,
},
labels: {
show: true
},
stacked: false,
ticks: {
fontColor: "#C4C4C4",
fontSize: 10,
precision: 0,
suggestedMax: 100,
suggestedMin: -100
},
afterBuildTicks:function (axis) {
axis.ticks = [0]
}
}
]
},
tooltips: {
mode: 'label',
bodySpacing: 10,
titleMarginBottom: 10,
titleFontSize: 14,
titleFontStyle: 'bold',
footerAlign: 'right',
callbacks: {
label: (tooltipItem, data) => {
const label = data.datasets[tooltipItem.datasetIndex].label || ''
const value = tooltipItem.value
return ` ${label}: ${value}`
}
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<canvas id="myChart" height="100"></canvas>
Thanks so much
I found the solution that use: gridLines options to draw chart with width is zero:
gridLines: {
display: true,
tickMarkLength: 10,
lineWidth: 0
}

Resources