chart.js 中的水平条形图水平、条形图、chart、js

2023-09-07 12:08:26 作者:独霸天下

我正在尝试使用 chart.js 2.3.0 绘制水平条形图 -

 var MeSeContext = document.getElementById("MeSeStatusCanvas").getContext("2d");var MeSeData = {标签: [我",SE"],数据集:[{标签:测试",数据:[100, 75],背景颜色:[#669911",#119966"],hoverBackgroundColor: ["#66A2EB", "#FCCE56"]}]};var MeSeChart = 新图表(MeSeContext,{类型:'水平条',数据:MeSeData,选项: {秤:{y轴:[{堆叠:真}]}}});

但它只显示一个条形图.我在这里错过了什么?

解决方案 代码详解 天啊,原来JS还可以这样玩 劈腿

您只能看到一张图表,因为您的数据的最低值(此处为 75)是刻度的左限.

如以下代码结果截图所示,如果你将鼠标悬停在刻度上,你仍然可以看到相关的数据,这意味着它就在这里.

你有两种方法可以解决这个问题:

将 xScale 刻度的 min 属性设置为您想要的值(当然可以看到):

var MeSeChart = new Chart(MeSeContext, {类型:'水平条',数据:MeSeData,选项: {秤:{x轴:[{滴答声:{min: 60//根据需要编辑值}}],y轴:[{堆叠:真}]}}});

您可以在此 jsFiddle 上将 min 设置为 60

beginAtZero 属性设置为 true,与将 min 设置为 0 相同:

xAxes: [{滴答声:{beginAtZero: 真}}],

您可以看到将 beginAtZero 属性设置为 true 在这个 jsFiddle 上.

I am trying to draw a horizontal bar chart using chart.js 2.3.0 -

 var MeSeContext = document.getElementById("MeSeStatusCanvas").getContext("2d");
    var MeSeData = {
        labels: [
            "ME",
            "SE"
        ],
        datasets: [
            {
                label: "Test",
                data: [100, 75],
                backgroundColor: ["#669911", "#119966" ],
                hoverBackgroundColor: ["#66A2EB", "#FCCE56"]
            }]
    };

var MeSeChart = new Chart(MeSeContext, {
    type: 'horizontalBar',
    data: MeSeData,
    options: {
        scales: {
            yAxes: [{
                stacked: true
            }]
        }

    }
});

But it only shows one bar. What did I miss here?

解决方案

You can see only one chart because the lowest value of your data (75 here) is the scale's left limit.

As shown in the following screenshot of your code's result, if you hover on the scale, you can still see the associated data, which means it is here.

You have two ways to fix this :

Set the min property of the xScale ticks to the value you want (enough to see it of course) :

var MeSeChart = new Chart(MeSeContext, {
    type: 'horizontalBar',
    data: MeSeData,
    options: {
        scales: {
            xAxes: [{
                ticks: {
                    min: 60 // Edit the value according to what you need
                }
            }],
            yAxes: [{
                stacked: true
            }]
        }
    }
});

You can see the result with a min set to 60 on this jsFiddle :

Set the beginAtZero property to true, which is the same as setting min to 0 :

xAxes: [{
    ticks: {
        beginAtZero: true
    }
}],

You can see the result with the beginAtZero property set to true on this jsFiddle.