【发布时间】:2016-10-17 19:48:46
【问题描述】:
我使用的是 Chart js 版本:2.1.4,但无法限制条形宽度。我在stackoverflow上找到了两个选项
barPercentage: 0.5
或
categorySpacing: 0
但没有一个适用于上述版本。有没有办法在不手动修改chart.js核心库的情况下解决这个问题?
谢谢
【问题讨论】:
标签: javascript jquery chart.js
我使用的是 Chart js 版本:2.1.4,但无法限制条形宽度。我在stackoverflow上找到了两个选项
barPercentage: 0.5
或
categorySpacing: 0
但没有一个适用于上述版本。有没有办法在不手动修改chart.js核心库的情况下解决这个问题?
谢谢
【问题讨论】:
标签: javascript jquery chart.js
你是对的:你必须编辑的属性是barPercentage。
但错误可能来自您编辑值的哪里。
正如您在bar chart options 中看到的:
名称:barPercentage
- 类型:数字
- 默认:0.9
- 描述 : 每个条的可用宽度的百分比 (0-1) 应在类别百分比内。 1.0 将采用整个类别宽度并将条形放在彼此旁边。 Read More
属性实际上存储在scales.xAxes(“xAxes 的选项”表中)。
所以你只需要这样编辑你的图表:
var options = {
scales: {
xAxes: [{
barPercentage: 0.4
}]
}
}
0.2):
var data = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: "My First dataset",
backgroundColor: "rgba(75,192,192,0.4)",
borderColor: "rgba(75,192,192,1)",
data: [65, 59, 75, 81, 56, 55, 40],
}]
};
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'bar',
data: data,
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}],
xAxes: [{
// Change here
barPercentage: 0.2
}]
}
}
});
console.log(myChart);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.6/Chart.js"></script>
<canvas id="myChart"></canvas>
如Release Version 2.2.0 - Candidate 2 中所述:
增强功能
- 现在可以手动配置条形图中条形的粗细。在正确的轴上使用新的
barThickness选项来设置条的厚度。- 等等……
【讨论】:
console.log() 之外,我很高兴知道您是如何调查这些问题的。
从 v2.7.2 开始,可以通过以下方式完成:
scales: {
xAxes: [{
maxBarThickness: 100,
}],
}
【讨论】:
对于 2.8+ 版本(显然可以追溯到 2.2),现在对条形厚度、最大厚度等进行了一些出色的控制。
根据Chart.js documentation,您可以像这样设置它们:
{
type: 'bar', // or 'horizontalBar'
data: ...,
options: {
scales: {
xAxes: [{
barThickness: 6, // number (pixels) or 'flex'
maxBarThickness: 8 // number (pixels)
}]
}
}
}
【讨论】:
如果您在 Angular 项目中使用 ng2-chart,则条形图配置如下所示:
npm install ng2-charts chart.js --save
在您的模块中导入“ng2-charts”。
import { ChartsModule } from 'ng2-charts';
现在条形图配置:
barChartOptions: ChartOptions = {
responsive: true,
maintainAspectRatio: false,
legend: {
display: false
},
};
barChartLabels: Label[] = ['2006', '2007', '2008', '2009', '2010', '2011', '2012'];
barChartType: ChartType = 'bar';
barChartLegend = true;
barChartPlugins = [];
barChartData: ChartDataSets[] = [
{
barThickness: 16,
barPercentage: 0.5,
data: [65, 59, 80],
label: 'Growth'
},
{
barThickness: 16,
barPercentage: 0.5,
data: [28, 48, 40],
label: 'Net'
}
];
barChartColors: Color[] = [
{ backgroundColor: '#24d2b5' },
{ backgroundColor: '#20aee3' },
];
现在是 HTML 部分:
<div class="bar-chart-wrapper">
<canvas baseChart [datasets]="barChartData" [colors]="barChartColors"
[labels]="barChartLabels"
[options]="barChartOptions" [plugins]="barChartPlugins" [legend]="barChartLegend"
[chartType]="barChartType">
</canvas>
</div>
您可以控制图表容器的高度
.bar-chart-wrapper {
height: 310px;
}
【讨论】:
barThickness 和 maxBarThickness(以前在 ChartOptions[] 中)现在是 ChartDataSets[] 的一部分。
【讨论】: