项目中需要使用简单的条形图,打算使用chart.js。由于整个项目使用了react,找到了react-chartjs。
柱状图
安装依赖
npm install --save react-chartjs
npm install --save chart.js@^1.1.1 react react-dom
使用bar
示例
import React, { Component } from 'react';
import { Bar as BarChart } from 'react-chartjs';
export default class Chart extends Component {
static propTypes = {
};
constructor(props) {
super(props);
this.state = {};
}
render() {
const data = {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [{
label: 'My First dataset',
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)',
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)',
],
borderWidth: 1,
data: [65, 59, 80, 81, 56, 55, 40],
}],
};
const options = {
scales: {
xAxes: [{
stacked: true,
}],
yAxes: [{
stacked: true,
}],
},
};
return (
<BarChart data={data} options={options} width="600" height="250" />
);
}
}
效果图
柱状图示例水平柱状图
需求是水平柱状图,但是react-chartjs
暂时不支持水平柱状图,issues
解决方法是升级到 react-chartjs-2
安装依赖
删除了上次安装的"chart.js": "1.1.1", "react-chartjs": "1.2.0"
npm install react-chartjs-2 chart.js --save
使用示例
import React, { Component } from 'react';
import { HorizontalBar } from 'react-chartjs-2';
export default class Chart extends Component {
static propTypes = {
};
constructor(props) {
super(props);
this.state = {};
}
render() {
const data = {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [
{
label: 'My First dataset',
backgroundColor: 'rgba(255,99,132,0.2)',
borderColor: 'rgba(255,99,132,1)',
borderWidth: 1,
hoverBackgroundColor: 'rgba(255,99,132,0.4)',
hoverBorderColor: 'rgba(255,99,132,1)',
data: [65, 59, 80, 81, 56, 55, 40],
},
],
};
return (
<HorizontalBar data={data} width="600" height="250" />
);
}
}
效果图
水平柱状图小问题
-
少量数据,bar太宽
设置最大宽度maxBarThickness
-
默认是从最小值开始计数,会导致,最小值对应的bar长度为0,设置
stacked
,使得所有的数据从0开始计数
...
const barOptions = {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [
{
label: '创建量',
backgroundColor: 'rgba(16, 142, 233, 0.7)',
borderColor: 'rgba(16, 142, 233, 0.7)',
borderWidth: 1,
hoverBackgroundColor: 'rgba(16, 142, 233, 1)',
hoverBorderColor: 'rgba(16, 142, 233, 1)',
data: [65, 59, 80, 81, 56, 55, 40],
},
],
};
const options = {
scales: {
yAxes: [{
stacked: true,
maxBarThickness: 50, // bar最大宽度
}],
xAxes: [{
stacked: true,
}],
},
};
return (
<HorizontalBar data={barOptions} options={options} />
);
从0开始计数
网友评论