问题描述
我在使用 com.byteowls.vaadin.chartjs ChartJs 时遇到以下问题 - 我不知道如何在不移除标签的情况下有条件地移除 gridLines。这是我用于创建 ChartJs 的以下代码: `
BarChartOptions options = barChartConfig.options();
options.title().text(title).display(true);
options.legend().position(Position.RIGHT);
options.tooltips().mode(InteractionMode.X);
options.legend().labels().BoxWidth(10).fontSize(10);
options.tooltips().position(Tooltips.PositionMode.NEAREST);
LinearScale yScale = new LinearScale();
yScale.stacked(true);
yScale.ticks().beginAtZero(true);
options.scales().add(Axis.Y,yScale);
DefaultScale xScale = new DefaultScale();
xScale.stacked(true);
xScale.ticks().autoSkip(false).callback("function(value,index,values){\n" +
"if(index % 2 !== 0){\n" +
" return undefined;\n" +
"\n" +
"} \n" +
"return value;\n" +
"\n" +
"}");
xScale.gridLines().linewidth(1).color("rgb(0,0)");
options.scales().add(Axis.X,xScale);
ChartJs horizontalStackedChart = new ChartJs(barChartConfig);
horizontalStackedChart.setHeight(70,Sizeable.Unit.PERCENTAGE);
horizontalStackedChart.setWidthFull();
return horizontalStackedChart;`
还有我想要的图像,但带有上一个图表中的标签:Chart Image 2
在我在互联网上发现有一个用于刻度的回调函数后,尝试了很多方法,但没有人帮助。我想在两个数据集之后显示 gridLines 在“图表图像 2”中的样子,但标签不见了。我不明白为什么会这样。实际上有可能吗? 在此先感谢您的帮助!
解决方法
您可以将 xAxis gridLines 的 lineColor 设置为一个函数,您可以在该函数中将要删除的所需线条设置为完全不透明的颜色。
示例:
var options = {
type: 'line',data: {
labels: ["Red","Blue","Yellow","Green","Purple","Orange"],datasets: [{
label: '# of Votes',data: [12,19,3,5,2,3],borderColor: 'red'
}]
},options: {
scales: {
x: {
grid: {
color: (ctx) => (ctx.index % 2 === 0 ? 'rgba(0,0)' : 'red')
}
}
}
}
}
var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx,options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.4.1/chart.js"></script>
</body>