I use chartjs for the charts and chartjs-plugin-databels for the data labels within each bar.
I need make value of line bold and leave the first part unchanged.
I try find solution in documentaion:
https://chartjs-plugin-datalabels.netlify.app/guide/labels.html#multiple-labels and https://www.chartjs.org/docs/latest/charts/bar.html, but there is not result.
Pictures:
It must look.
vs
It looks.
My code
import _ from "lodash";
import { Bar } from "react-chartjs-2";
import ChartDataLabels from "chartjs-plugin-datalabels";
const options = {
indexAxis: "y" as const,
responsive: true,
elements: {
bar: {
borderWidth: 1,
},
},
scales: {
y: {
ticks: {
display: false,
},
grid: {
display: false,
},
},
x: {
grid: {
borderDash: [10, 10],
},
},
},
plugins: {
datalabels: {
anchor: `start` as "start", import _ from "lodash";
align: `end` as "end", import _ from "lodash";
formatter: function (value: any, context: any) {
return (
context.chart.data.labels[context.dataIndex] +
": " +
context.dataset.data[context.dataIndex]
);
},
},
legend: {
display: false,
},
title: {
display: false,
},
},
};
const labels = [
"Some label 1",
"Some label 1",
"Some label 1",
"Some label 1",
"Some label 1",
"Other",
];
const data = {
labels,
datasets: [
{
data: labels.map(() => Math.floor(Math.random() * 10000)), // random values
maxBarThickness: 28,
inflateAmount: 3,
},
],
};
const HorizontalBarChart = () => {
return (
<Bar options={options} data={data} plugins={[ChartDataLabels]} />
);
};
What information to add to make the question clearer?
Related
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}
/>
</>
);
}
I'm using react-chartjs-2 v4.1 with ChartJS v3.8 in typescript.
I'd like to draw a horizontal line through my bar graph as shown below:
I find many half-written examples of which I cannot create a functional one. I couldn't find any complete, working example on how to use annotations.
My Code
I've added the chartjs-plugin-annotation package to my project.
Below is the code for a react component showing the graph of the screenshot. The annotation, however, does not work.
Can anyone tell me what's wrong with the code?
import React from 'react';
import { Bar } from 'react-chartjs-2';
export const MyChart: React.FC = () => {
const options2 = {
plugins: {
legend: {
display: false,
},
annotation: {
annotations: [
{
id: 'a-line-1',
type: 'line',
mode: 'horizontal',
scaleID: 'y',
value: 1.0,
borderColor: 'red',
borderWidth: 4,
label: {
enabled: false,
content: 'Test label',
},
},
],
},
},
};
const data2 = {
labels: [ 'a', 'b'],
datasets: [ { data: [1, 2] } ],
};
return (<Bar options={options2} data={data2} height={150} />
);
};
You dont import and register the annotation plugin:
import { Chart } from 'chart.js';
import annotationPlugin from 'chartjs-plugin-annotation';
Chart.register(annotationPlugin);
Based on LeeLenalee's answer here's a fully working example.
Changes to code in question:
import and register annotationPlugin
set annotation type to type: 'line' as const (not just type: 'line'). Otherwise typescript complains.
import React from 'react';
import { Bar } from 'react-chartjs-2';
import { Chart } from 'chart.js';
import annotationPlugin from 'chartjs-plugin-annotation';
Chart.register(annotationPlugin);
export const MyChart: React.FC = () => {
const options2 = {
plugins: {
legend: {
display: false,
},
annotation: {
annotations: [
{
id: 'a-line-1',
type: 'line' as const, // important, otherwise typescript complains
mode: 'horizontal',
scaleID: 'y',
value: 1.0,
borderColor: 'red',
borderWidth: 4,
label: {
enabled: false,
content: 'Test label',
},
},
],
},
},
};
const data2 = {
labels: [ 'a', 'b'],
datasets: [ { data: [1, 2] } ],
};
return (<Bar options={options2} data={data2} height={150} />
);
};
Screen Ratio 100%
enter image description here
Screen Ratio 70%
enter image description here
const chartData = {
type: 'area',
height: 95,
options: {
chart: {
id: 'rental-Chart',
sparkline: {
enabled: true,
},
},
dataLabels: {
enabled: false,
},
stroke: {
curve: 'smooth',
width: 1.3,
},
tooltip: {
fixed: {
enabled: false,
},
x: {
show: true,
},
y: {
title: 'Ticket ',
},
marker: {
show: false,
},
},
},
series: [
{
name: 'Number of Rentals : ',
data: [0, 5, 3, 15, 20, 10, 22],
},
],
};
export default chartData;
import React, { useEffect, useState } from 'react';
import { Card, Grid, Typography } from '#mui/material';
import ApexCharts from 'apexcharts';
import Chart from 'react-apexcharts';
import chartData from './Product-Stock-Chart';
function BajajAreaChartCard() {
useEffect(() => {
const newSupportChart = {
...chartData.options,
chart: {
width: '100%',
},
};
ApexCharts.exec(`rental-Chart`, 'updateOptions', newSupportChart, true);
}, []);
return (
<Chart {...chartData} />
);
}
export default BajajAreaChartCard;
It works normally when it is the default size, but if reduce the size, the size of the chart changes as shown in the picture.
I don`t know what to do to solve this problem..
please help me..
I am trying to find a way in the apex chart. By which if user zoom on the year graph then the user should be able to get month data when they zoom on month data this should show the day data.
But I am not able to figure out if its possible in apex chart or not.
This is how my graph look like right now.
import React from "react";
import ReactApexChart from "react-apexcharts";
interface StackedGraphProps {}
type SeriesType = {
name: string;
data: number[];
};
interface StackedGraphState {
series: SeriesType[];
options: any;
}
class StackedBarGraph extends React.Component<
StackedGraphProps,
StackedGraphState
> {
constructor(props: any) {
super(props);
this.state = {
series: [
{
name: "Marine Sprite",
data: [44, 55, 41, 37, 22, 43, 21],
},
{
name: "Striking Calf",
data: [53, 32, 33, 52, 13, 43, 32],
},
{
name: "Tank Picture",
data: [12, 17, 11, 9, 15, 11, 20],
},
],
options: {
chart: {
events: {
zoomed: function (chartContext: any, { xaxis, yaxis }) {
console.log("xAxis", xaxis, yaxis);
},
selection: function (chartContext: any, { xaxis, yaxis }) {
console.log("Selecton", xaxis, yaxis);
},
dataPointSelection: (
event: any,
chartContext: any,
config: any
) => {
console.log("datapoint", chartContext, config);
},
},
zoom: {
enabled: true,
type: "x",
autoScaleYaxis: false,
// zoomedArea: {
// fill: {
// color: "#90CAF9",
// opacity: 0.4,
// },
// stroke: {
// color: "#0D47A1",
// opacity: 0.4,
// width: 1,
// },
// },
},
type: "bar",
height: 350,
stacked: true,
},
toolbar: {
show: true,
},
plotOptions: {
bar: {
horizontal: false,
},
},
stroke: {
width: 1,
colors: ["#fff"],
},
grid: {
row: {
colors: ["#fff", "#f2f2f2f2"],
},
},
title: {
text: "",
},
xaxis: {
tickPlacement: "on",
categories: [2008, 2009, 2010, 2011, 2012, 2013, 2014],
labels: {
formatter: function (val: any) {
return val + "K";
},
},
},
yaxis: {
title: {
text: undefined,
},
},
tooltip: {
y: {
formatter: function (val: any) {
return val + "K";
},
},
},
fill: {
opacity: 1,
},
legend: {
position: "top",
horizontalAlign: "left",
offsetX: 40,
},
},
};
}
render() {
return (
<div id="chart">
<ReactApexChart
zoomEnabled={true}
options={this.state.options}
series={this.state.series}
type="bar"
height={350}
/>
</div>
);
}
}
export default StackedBarGraph;
I'm using echarts and i'm trying to emphasis the "current picked bar" by adding background color.
I want to be able to click on one of the bars, and by doing so the month will change and the background color will be applied on the back of that month.
Makes sense?
Here's a codesandbox that emphasis my idea:
https://codesandbox.io/s/flamboyant-cloud-zy44j?file=/src/App.js
But going over and documentation it seems as though there is no option to add backgroundColor to just one category / bar. I tried using another series but that did not work.
I'm also attaching pictures to explain what should be.
And also attaching the code.
import React, { useState } from "react";
import "./styles.css";
import ReactEcharts from "echarts-for-react";
import moment from "moment";
export default function App() {
const [month, setMonth] = useState(0);
const onChartClick = (params) => {
const monthClicked = moment().month(params.name).month();
setMonth(monthClicked);
};
console.log(month);
const renderChart = () => {
const _onEvents = {
click: onChartClick
};
const option = {
maintainAspectRatio: false,
tooltip: {
trigger: "item"
},
grid: {
left: "0px",
right: "0px",
bottom: "0px",
top: "0px",
containLabel: false,
show: false
},
xAxis: {
position: "top",
axisLine: {
show: false
},
axisTick: {
show: false
},
axisLabel: {
inside: true,
color: "#74818f",
fontFamily: "SegoePro-Regular",
fontSize: 12
},
splitNumber: 1,
splitLine: {
show: true,
lineStyle: {
color: [
"#ffffff",
"#eaeaea",
"#eaeaea",
"#eaeaea",
"#eaeaea",
"#eaeaea",
"#eaeaea",
"#eaeaea",
"#eaeaea",
"#eaeaea",
"#eaeaea",
"#eaeaea",
"#ffffff",
"#ffffff",
"#ffffff"
]
}
},
type: "category",
data: [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
]
},
yAxis: {
scale: true,
type: "value",
axisLabel: {
show: false
},
axisTick: {
show: false
},
axisLine: {
show: false,
onZero: false
},
splitLine: {
show: false
}
},
series: [
{
name: "Monthly Income",
type: "bar",
barWidth: "30%",
barGap: "-20%",
label: {
show: true,
position: "top",
fontSize: 12,
fontFamily: "SegoePro-Bold",
color: "#3d70ff"
},
itemStyle: {
opacity: 0.7,
color: "#3d70ff"
},
emphasis: {
itemStyle: {
opacity: 1
}
},
tooltip: {},
data: [
8700,
8700,
10400,
8699,
8699,
8699,
8699,
8699,
11643.46,
0,
0,
0
],
markArea: {
silent: true,
data: [
[
{
coord: [0, 0]
},
{
coord: [100, 100]
}
]
],
itemStyle: {
color: "#f5f7fa"
},
label: {
show: false
}
}
}
]
};
const chartStyle = 280;
return (
<div id="chart_div">
<div className="chart-wrapper">
<ReactEcharts
onEvents={_onEvents}
option={option}
style={{ height: chartStyle }}
/>
</div>
</div>
);
};
return renderChart();
}
the requirement is unachievable with this library. you can make x-axis clickable by triggerEvent and do something with it; but adding a background or any other style on a "clicked" bar ( or axis ) needs a dedicated state; clicked state; which this library doesn't have; it listens to click events, but doesn't keep it on individual elements; so you can't style it based on a state that doesn't exist;
I was thinking about a workaround to make it happen by some applying css styles on clicked/hovered bars to fake the effect somehow but all the content are rendered inside a canvas, so no option remains; either use another library or write a chart drawer component yourself or forget this specific styling based on click;