【发布时间】:2021-11-24 18:55:15
【问题描述】:
我这里有条形图:
import React, { Component, useState, useEffect } from "react";
import { Bar } from "react-chartjs-2";
import { months } from "../../helpers/utils";
import Axios from "axios"; //axios library to make requests to api
// Chart.defaults.global.defaultFontFamily = "Roboto, sans-serif";
function BarChart() {
//retrieving data from api
const [intentsList, setintentsList] = useState([]);
useEffect(() => {
Axios.get("http://localhost:3001/countintents").then((response) => {
setintentsList(response.data);
console.log(response.data);
});
}, []);
// BarChart
//const labels = Object.keys(intentsList);
const data = {
labels: Object.keys(intentsList),
datasets: [
{
axis: "y",
label: "My First Dataset",
data: Object.values(intentsList),
fill: false,
backgroundColor: [
"rgba(255, 99, 132, 0.2)",
"rgba(255, 159, 64, 0.2)",
"rgba(255, 205, 86, 0.2)",
"rgba(75, 192, 192, 0.2)",
"rgba(54, 162, 235, 0.2)",
"rgba(153, 102, 255, 0.2)",
"rgba(201, 203, 207, 0.2)",
],
borderColor: [
"rgb(255, 99, 132)",
"rgb(255, 159, 64)",
"rgb(255, 205, 86)",
"rgb(75, 192, 192)",
"rgb(54, 162, 235)",
"rgb(153, 102, 255)",
"rgb(201, 203, 207)",
],
borderWidth: 1,
},
],
};
const options = {
indexAxis: "y",
// Elements options apply to all of the options unless overridden in a dataset
// In this case, we are setting the border of each horizontal bar to be 2px wide
elements: {
bar: {
borderWidth: 2,
},
},
responsive: true,
plugins: {
legend: {
position: "right",
display: false,
},
title: {
display: true,
text: "Chart.js Horizontal Bar Chart",
},
},
};
return (
<div>
<Bar data={data} options={options} /> {/* Props */}
</div>
);
}
export default BarChart;
后端代码:
app.get("/countintents", (req, res) => {
db.query(
"SELECT SUM(CASE WHEN intent IN ('Products', 'Land Transport') THEN 1 END) AS products, SUM(CASE WHEN intent IN ('Air Freight', 'Industry Solutions', 'Aerospace and Defense') THEN 1 END) AS industry_solutions, SUM(CASE WHEN intent in ('Profile', 'Contact Us') THEN 1 END) AS about_us FROM data_analytics",
(err, result) => {
if (err) {
console.log(err);
} else {
res.send(result);
}
}
);
});
这个后端代码允许我在 api 端点 /countintents 中检索这些数据 即:[{"products":2,"industry_solutions":3,"about_us":2}]
这是在我收到它的intentsList 中。我的问题是如何根据我收到的内容填充我的条形图以将标签显示为 Products、Industry_solutions、About_us 和 data 作为 2、3、2。
【问题讨论】:
标签: javascript mysql sql node.js reactjs