javascript - Remove padding from chartJs horizontal bar chart
问题描述
Hey :) thanks in advance for helping me out on this issue.
I have a horizontal chart in ChartJs with some dummy info. I currently want to line it up with the statistic above it. In ChartJs the charts get rendered inside a <canvas>
tag. I want to remove the spacing in the chart. I'm assuming this is padding but its not on the canvas it's within the chart itself. I've read up on the docs and tried a few of the choices.
Just some extra info, I customized the chart and it now looks like this:
- Removed the legend
- Flipped the labels
- Changed the label colour
- Removed the grid lines
HTML:
<canvas id="myChart" width="400" height="150"></canvas>
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'horizontalBar',
data: {
labels: ['1', '2'],
datasets: [{
label: 'Money in',
data: [5, 19],
backgroundColor: [
'rgb(0,51,160)',
'rgb(26,121,191)'
],
borderWidth: 0
}]
},
options: {
scales: {
yAxes: [{
ticks: {
fontColor: 'white',
display: true,
position: top,
mirror: true,
beginAtZero: true,
fontSize: 17,
padding: -9,
z: 1
},
gridLines: {
display: false
}
}],
xAxes: [{
gridLines: {
display: false
},
ticks: {
beginAtZero: true,
display: false
}
}]
},
legend: {
display: false
}
}
});
解决方案
您可以定义layout
负左填充如下:
options: {
layout: {
padding: {
left: -10
}
},
...
请查看以下代码片段,其中图表画布用边框定义,以强调与前面文本的对齐。
var myChart = new Chart(document.getElementById('myChart'), {
type: 'horizontalBar',
data: {
labels: ['1', '2'],
datasets: [{
label: 'Money in',
data: [5, 19],
backgroundColor: ['rgb(0,51,160)', 'rgb(26,121,191)'],
borderWidth: 0
}]
},
options: {
layout: {
padding: {
left: -10
}
},
scales: {
yAxes: [{
ticks: {
fontColor: 'white',
mirror: true,
beginAtZero: true,
fontSize: 17,
padding: -9,
z: 1
},
gridLines: {
display: false
}
}],
xAxes: [{
gridLines: {
display: false
},
ticks: {
beginAtZero: true,
display: false
}
}]
},
legend: {
display: false
}
}
});
canvas{
max-width: 300px;
border: 1px solid #000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.js"></script>
<p>Text here</p>
<canvas id="myChart" width="400" height="150"></canvas>
推荐阅读
- python - TensorFlow:添加具有恒定值的维度(列)
- javascript - Express 路由器无法识别 mongoose 型号
- ssh - 如果有人拥有我的私钥,我可以删除它以及它可能拥有的所有权限吗?
- vue.js - VueJS + Firestore- 自动保存投票
- python - python 3中带有嵌套ifs的列表理解变量范围
- python - 在 Python 中使用 Pytesseract 检测图像中的文本
- angular - 我的 Angular ngrx/store 效果没有被触发
- javascript - 带有 if 语句和 2-dim 数组 javascript 的嵌套 for 循环
- pandas - 如何绘制熊猫数据框的 2 列,不包括第三列选择的行
- python - plotly scattermapbox - 标记/绘图坐标问题