This code snippet demonstrates how to create a bar chart using React and the Chart.js library. The bar chart shows the evolution of carbon emissions over time to track improvement in a strategy. It is a useful visualization tool for data analysis and reporting.
Code
import React from "react";
import { Bar } from "react-chartjs-2";
import { useParams } from "react-router-dom";
import useFetch from "../../hooks/useFetch";
import Spinner from "../../shared/Spinner";
import { optionsReportsComparison } from "../shared/options";
import ChartDataLabels from "chartjs-plugin-datalabels";
const data = {
datasets: [
{
type: "line",
label: "Dataset 1",
borderColor: "rgb(255, 99, 132)",
data: {
2021: 3,
2022: 2,
},
stack: "Scenario - Test analytics - Februaryy",
},
{
type: "bar",
label: "Dataset 2",
backgroundColor: "rgb(75, 192, 192)",
data: {
2021: 1.25,
2022: 1.25,
},
stack: "Scenario - Test analytics - February",
},
],
};
const ScenarioTargets = () => {
const { reportPk } = useParams();
// const { data } = useFetch(`/api/analytics/get-scenario-target-chart/${reportPk}/?model-name=scope_fk&group-by=report`);
if (!data) {
return <Spinner />;
} else {
const tweakData = () =>
data.datasets.map((d) => {
d.barPercentage = 0.4;
d.categoryPercentage = 0.5;
d.borderRadius = 10;
if (d.label === "Scope 3") {
d.padding = { top: 20 };
d.datalabels = {
labels: {
report: {
backgroundColor: "white",
borderRadius: 4,
borderWidth: 1,
borderColor: "#4a5568",
padding: {
top: 2,
bottom: 2,
left: 4,
right: 4,
},
offset: 4,
align: "end",
anchor: "end",
color: "#4a5568",
font: { size: 10 },
formatter: function (value, ctx) {
return ctx.dataset.info;
},
},
},
};
}
});
tweakData();
// const tweakData = () =>
// data.datasets.map((d) => {
// d.barThickness = 30;
// d.borderRadius = 10;
// delete d.stack;
// });
// tweakData();
return (
<div className="p-10 bg-white shadow-lg rounded-box">
<h3 className="text-xl uppercase font-bold mb-4 text-gray-700">Scenarios targets</h3>
<p className="text-gray-500 mb-20">Evolution of carbon emissions over time to track improvement in your strategy.</p>
<div className="flex items-center justify-center">
<Bar options={optionsReportsComparison} data={data} plugins={[ChartDataLabels]} />
</div>
</div>
);
}
};
export default ScenarioTargets;
Code Explanation
First, we import the necessary dependencies for our code snippet:
import React from "react";
import { Bar } from "react-chartjs-2";
import { useParams } from "react-router-dom";
import useFetch from "../../hooks/useFetch";
import Spinner from "../../shared/Spinner";
import { optionsReportsComparison } from "../shared/options";
import ChartDataLabels from "chartjs-plugin-datalabels";
Next, we define the data for our bar chart:
const data = {
datasets: [
{
type: "line",
label: "Dataset 1",
borderColor: "rgb(255, 99, 132)",
data: {
2021: 3,
2022: 2,
},
stack: "Scenario - Test analytics - Februaryy",
},
{
type: "bar",
label: "Dataset 2",
backgroundColor: "rgb(75, 192, 192)",
data: {
2021: 1.25,
2022: 1.25,
},
stack: "Scenario - Test analytics - February",
},
],
};
Then, we define the component ScenarioTargets
using a functional component with React hooks:
const ScenarioTargets = () => {
const { reportPk } = useParams();
// Fetch data using the useFetch hook
if (!data) {
return
} else {
const tweakData = () =>
data.datasets.map((d) => {
// Modify dataset properties
});
tweakData();
return (
<div className="p-10 bg-white shadow-lg rounded-box">
<h3 className="text-xl uppercase font-bold mb-4 text-gray-700">Scenarios targets</h3>
<p className="text-gray-500 mb-20">Evolution of carbon emissions over time to track improvement in your strategy.</p>
<div className="flex items-center justify-center">
<Bar options={optionsReportsComparison} data={data} plugins={[ChartDataLabels]} />
</div>
</div>
);
}
};
In the above component, we have the following functionalities:
1. Fetching data using the useFetch
hook (currently commented out).
2. Manipulating the dataset using the tweakData
function.
3. Rendering the bar chart using the Bar
component from react-chartjs-2
.
4. Applying custom styling and options to the bar chart.
Conclusion
In this code snippet, we have learned how to create a bar chart using React and Chart.js. The bar chart is used to visualize the evolution of carbon emissions over time, providing a visual representation of the improvement in a strategy. It is a powerful tool for data analysis and reporting. By following this example, you can easily create your own bar charts in React applications.
Also checkout the following codes.
How to Truncate a String in JavaScript: Program to Limit Characters
How to Use the log() Function in Python