2017-03-08 153 views
0

是否可以针对不同的数据集具有不同的条宽?我在一个堆栈中有几个数据集,另一个数据集在它自己的堆栈中。单个数据集应该比其他堆栈更窄Chart.js条形图中的多个条宽度

Example。这里我复制了左边的堆栈,导致它是正确堆栈宽度的两倍。这打破了一定的影响,其中包括非零边界

var data = { 
    labels: ["1", "2", "3", "4", "5"], 
    datasets: [ 
    { 
     label: "d1", 
     backgroundColor: "rgba(182,127,0,1)", 
     borderColor: "rgba(117,61,41,1)", 
     borderWidth: 1, 
     data: [42, 78, 64, 90, 97], 
     stack: "s1" 
    }, 
    { 
     label: "d2", 
     backgroundColor: "rgba(71,161,65,1)", 
     borderColor: "rgba(36,93,56,1)", 
     borderWidth: 1, 
     data: [27, 63, 46, 64, 43], 
     stack: "s1" 
    }, 
    { 
     label: "d3", 
     backgroundColor: "rgba(255,141,106,1)", 
     borderColor: "rgba(99,60,32,1)", 
     borderWidth: 1, 
     data: [18, 50, 23, 83, 35], 
     stack: "s1" 
    }, 
    { 
     label: "d1", 
     backgroundColor: "rgba(182,127,0,1)", 
     borderColor: "rgba(117,61,41,1)", 
     borderWidth: 1, 
     data: [42, 78, 64, 90, 97], 
     stack: "s1b" 
    }, 
    { 
     label: "d2", 
     backgroundColor: "rgba(71,161,65,1)", 
     borderColor: "rgba(36,93,56,1)", 
     borderWidth: 1, 
     data: [27, 63, 46, 64, 43], 
     stack: "s1b" 
    }, 
    { 
     label: "d3", 
     backgroundColor: "rgba(255,141,106,1)", 
     borderColor: "rgba(99,60,32,1)", 
     borderWidth: 1, 
     data: [18, 50, 23, 83, 35], 
     stack: "s1b" 
    }, 
    { 
     label: "d4", 
     backgroundColor: "rgba(160,160,160,1)", 
     borderColor: "rgba(60,60,60,1)", 
     borderWidth: 1, 
     data: [152, 141, 170, 194, 128], 
     stack: "s2", 
     barPercentage: 0.3 
    } 
    ] 
}; 
var options = { 
    scales: { 
    xAxes: [{ 
     categoryPercentage: 0.6, 
     barPercentage: 1 
    }] 
    }, 
    legend: { 
    display: false 
    } 
}; 

var barChart = new Chart($("#myChart"), { 
    type: 'bar', 
    data: data, 
    options: options 
}); 

回答

1

这实际上可以在chart.js中做,但解决方案有点“hackish”。其要点是您可以创建第二个x轴刻度并将barThickness属性设置为小于其他轴的值。然后,将您的数据集分配给此访问权限,最后将比例显示设置为false。

您最终会得到一个轴上的一些数据集,而另一个数据集则隐藏在另一个不同的轴上。其他一切仍然有效(没有像你在你的问题中提到的破坏效果)。

以下是您的选择的样子。

var options = { 
    scales: { 
    xAxes: [{ 
     categoryPercentage: 0.6, 
     barPercentage: 1, 
    }, { 
     id: 'x-axis-2', 
     type: 'category', 
     display: false, 
     categoryPercentage: 0.6, 
     barPercentage: 1, 
     barThickness: 20, 
     gridLines: { 
     offsetGridLines: true 
     } 
    }], 
    }, 
    legend: { 
    display: false 
    } 
}; 

你必须确保你添加xAxisID: 'x-axis-2'你要绑定到新中轴线为准数据集。

这是一个codepen example演示所有这一切。

您甚至可以通过更改周围的比例来为水平条形图执行此操作。看到这个codepen example显示这一点。

+0

看起来很像我需要的东西,但它是否适用于水平条形图?我尝试切换你的例子,但第二轴不再显示http://codepen.io/MalikDrako/pen/RpjLRd?editors=0010它也看起来像在某些地方交换轴,但不是别人 - 尝试设置tye类型以y轴为对数,但似乎将其设置为垂直轴。 –

+0

是的,你可以看到我更新的答案中的例子 – jordanwillis