reactjs - react 我想在 React 图表中隐藏 y 轴的数值和提示信息
我正在使用 react-chart-2。
当我悬停在折线图上时,会显示提示框,但我想在悬停折线图时隐藏提示框。
我还想隐藏折线图左侧(y 轴)上的数字 0、0.1、0.2 到 1。
我如何实现隐藏折线图的 y 轴?
另外,如何在折线图中隐藏提示框?
代码
import React from "react";
import { Bar } from "react-chartjs-2";
const data = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "Sales",
type: "line",
data: [51, 300, 40, 49, 60, 37, 40],
fill: false,
borderColor: "#555555",
backgroundColor: "#555555",
pointBorderColor: "#000000",
pointBackgroundColor: "#EC932F",
pointHoverBackgroundColor: "#EC932F",
pointHoverBorderColor: "#EC932F",
yAxisID: "y-axis-1"
},
{
type: "bar",
label: "Visitor",
data: [200, 185, 590, 621, 250, 400, 95],
fill: false,
backgroundColor: "#F7C520",
borderColor: "#F7C520",
hoverBackgroundColor: "#E6B71E",
hoverBorderColor: "#E6B71E",
yAxisID: "y-axis-1"
}
]
};
const options = {
responsive: true,
tooltips: {
mode: "label"
},
elements: {
line: {
fill: false
}
},
scales: {
xAxes: [
{
display: true,
gridLines: {
display: true
}
}
],
yAxes: [
{
type: "linear",
display: true,
position: "left",
id: "y-axis-1",
gridLines: {
display: true
}
},
{
type: "linear",
display: true,
position: "right",
id: "y-axis-2",
gridLines: {
display: false
}
}
]
}
};
class MixExample extends React.Component {
render() {
return (
<div>
<h2>Mixed data Example</h2>
<Bar data={data} options={options} />
</div>
);
}
}
export default MixExample;
答案#1
react-chartjs-2 有两个与此问题相关的主要版本:v2,支持 chart.js 2.9.4 及以下版本;v3,显著改变了许多选项和配置,并支持 chart.js 3.0.0 及以上版本。
您提供的 codesandbox 链接的原始分支使用的是 chart.js: 2.9.4 和 react-chartjs-2: 2.1.1,这与您提供的沙箱链接不同,后者使用的是 chart.js: 3.5.1 和 react-chartjs-2: 3.0.4。值得注意的是,您没有像这样构建 options 对象
scales: {
x-axes: [ /* array of axis options... */],
y-axes: [ /* array of axis options... */],
}
每个坐标轴都有一个 axisID 属性,你可以用 axisID 作为键,将原始选项对象的其余部分作为值来组织它们,例如:
scales: {
"x-axis-1": {
display: true,
gridLines: {
display: false
}
},
"y-axis-1": {
type: "linear",
display: false,
position: "left"
}
}
此外,根据 chart.js 文档,工具提示是插件的一部分,可以通过将工具提示移入插件来禁用它:
图表工具提示的全局选项在
Chart.defaults.plugins.tooltip中定义
因此,要完全禁用工具提示:
plugins: {
tooltip: {
enabled: false
}
}
既然你只想为单个数据集禁用工具提示,这里找到的解决方案可能有一些用处,但我自己都没有尝试过。也有可能将 Chart.JS 工具提示的全局默认值设置为 false,然后按数据集逐一启用,如这里所示,可以通过 react-chartjs-2 的图表引用访问它。
对于那种级别的自定义,我强烈建议从头开始使用最新版本的 react-chartjs-2 及其中的示例,而不是你当前配置为 v2 的起点。
