跳过 chartjs 刻度标签,如果它们重叠。

huangapple go评论76阅读模式
英文:

Skip chartjs tick label if they overlap

问题

这是从此帖子继续下来的最终部分。

我有以下(持续进行中的)Chart.js 设置(感谢 @winnder_joiner)。

const d0 = new Date("2023-02-15T00:00:00.721Z").getTime();
const d1 = new Date("2023-02-15T00:03:00.721Z").getTime();
const d2 = new Date("2023-02-15T02:30:00.721Z").getTime();
const d3 = new Date("2023-02-15T03:20:00.721Z").getTime();
const d4 = new Date("2023-02-15T05:05:00.721Z").getTime();
let values = [d0, d1, d2, d3, d4];

let data = {
  labels: [''],
  datasets: [{
    label: 'up',
    axis: 'y',
    data: [d1],
    backgroundColor: 'red',
  }, {
    label: 'down',
    //axis: 'y',
    data: [d2],
    backgroundColor: 'yellow',
  }, {
    label: 'out',
    // axis: 'y',
    data: [d3],
    backgroundColor: 'green',
  }, {
    label: 'up',
    // axis: 'y',
    data: [d4],
    backgroundColor: 'red',
  }]
};

const config = {
  data,
  type: 'bar',
  options: {
    elements: {
      bar: {
        borderWidth: 0
      }
    },
    ticks: {
      display: true
    },
    interaction: {
      mode: 'dataset'
    },
    // tooltip: {
    //    mode: 'dataset'  
    // },
    hover: {
      mode: 'dataset'
    },
    plugins: {
      legend: {
        display: false,
      },
      title: {
        display: false,
      },
    },
    indexAxis: 'y',
    responsive: true,
    maintainAspectRatio: false,
    scales: {
      x: {
        border: {
          display: false,
        },
        min: d0,
        ticks: {
          source: 'auto',
          maxRotation: 80,
          minRotation: 60,
          autoSkip: false,
          // autoSkipPadding: 0,
          // padding: 0,
          // align: 'inner',
          // crossAlign: 'near',
          callback: function (value, index, ticks) {
            return moment(value).format('HH:mm');
          }
        },
        afterBuildTicks: axis => axis.ticks = values.map(v => ({ value: v }))
      },
      y: {
        grid: {
          display: false
        },
        stacked: true
      },
    }
  }
};

new Chart(document.getElementById("chart"), config);

这也可以在这里看到。

回调函数afterBuildTicks允许在实际数据点处绘制刻度标签,这很好。如果我们不使用afterBuildTicks,它会自动计算一些点来绘制刻度标签。

唯一的问题是,如果两个数据点非常接近,例如,标签会重叠...

我的问题是...
是否有办法在存在重叠的情况下跳过绘制刻度标签?

英文:

This is the final piece following on from this post

I have the following (ongoing) chartjs setup (thanks to @winnder_joiner)

	const d0 = new Date("2023-02-15T00:00:00.721Z").getTime()
const d1 = new Date("2023-02-15T00:03:00.721Z").getTime()
const d2 = new Date("2023-02-15T02:30:00.721Z").getTime()
const d3 = new Date("2023-02-15T03:20:00.721Z").getTime()
const d4 = new Date("2023-02-15T05:05:00.721Z").getTime()
let values = [d0, d1, d2, d3, d4];
let data = {
labels: [''],
datasets: [{
label: 'up',
axis: 'y',
data: [d1],
backgroundColor: 'red',
},{
label: 'down',
//axis: 'y',
data: [d2],
backgroundColor: 'yellow',
},{
label: 'out',
// axis: 'y',
data: [d3],
backgroundColor: 'green',
},{
label: 'up',
//   axis: 'y',
data: [d4],
backgroundColor: 'red',
}
]
};
const config = {
data,
type: 'bar',
options:{
elements: {
bar: {
borderWidth: 0
}
},
ticks: {
display: true
},
interaction: {
mode: 'dataset'
},
// tooltip: {
//    mode: 'dataset'  
// },
hover: {
mode: 'dataset'            
},      
plugins: {
legend: {
display: false,
},
title: {
display: false,
},
},
indexAxis: 'y',
responsive: true,
maintainAspectRatio: false,
scales: {
x: {
border: {
display: false,
},
min: d0,
ticks: {
source: 'auto',
maxRotation: 80,
minRotation: 60,
autoSkip: false,   
// autoSkipPadding: 0,
//padding: 0,
//align: 'inner',
//crossAlign: 'near',
callback: function(value, index, ticks) {
return moment(value).format('HH:mm');
}
},
afterBuildTicks: axis => axis.ticks = values.map(v => ({ value: v }))
},
y: {
grid: {
display: false
},
stacked: true
},
}    
}};
new Chart(document.getElementById("chart"), config);

This can also be seen here

The callback afterBuildTicks allows the ticks to be draw at the actual data points - which is good. If we don't use afterBuildTicks it just automatically works out some points to draw the ticks.

The only problem occurs if two data points happen to be very close, eg we get the lables overlapping....

跳过 chartjs 刻度标签,如果它们重叠。

My question here is..
Is there any way to have it skip drawing the ticks label if there is such an overlap?

答案1

得分: 1

以下是翻译好的部分:

"Well As far as I know, you can prevent the overlap with the config (more than you already did), BUT you could do it yourself just calculating the diff between the ticks. You would have to eyeball die minDiff, and in the tick generation return null if the ticks are too close."

"我了解的情况是,您可以通过配置来防止重叠(比您已经做的更多),但您也可以自己计算刻度之间的差异。您需要自己确定 minDiff,并在生成刻度时,如果刻度太接近,返回 null。"

"I tried it in the following example:"
"(It is not prefect, because if there are many after each other, that are too short, "too many" ticks might be skipped)"
"> _In this example 11:29 could/should be shown, because 11:00 was not displayed."

"我在以下示例中尝试过:"
"(这不是完美的,因为如果有很多相邻的刻度太短,可能会跳过“太多”刻度)"
"> 在这个示例中,11:29 可能/应该显示,因为 11:00 没有显示。"

接下来是代码部分,不进行翻译。

英文:

Well As far as I know, you can prevent the overlap with the config (more than you already did), BUT you could do it yourself just calculating the diff between the ticks. You would have to eyeball die minDiff, and in the tick generation return null if the ticks are too close.

I tried it in the following example:
(It is not prefect, because if there are many after each other, that are too short, "too many" ticks might be skipped)

> In this example 11:29 could/should be shown, because 11:00 was not displayed.

<!-- begin snippet: js hide: false console: false babel: false -->

<!-- language: lang-js -->

const d0 = moment.duration(&#39;08:50:00&#39;).asMinutes();
const d1 = moment.duration(&#39;09:00:00&#39;).asMinutes();
const d2 = moment.duration(&#39;10:45:00&#39;).asMinutes();
const d22 = moment.duration(&#39;11:00:00&#39;).asMinutes();
const d23 = moment.duration(&#39;11:29:00&#39;).asMinutes();
const d3 = moment.duration(&#39;17:35:00&#39;).asMinutes();
const d4 = moment.duration(&#39;19:00:00&#39;).asMinutes();
let values = [d0, d1, d2, d22, d23, d3, d4];
let data = {
labels: [&#39;&#39;],
datasets: [{
label: &#39;up&#39;,
axis: &#39;y&#39;,
data: [d1],
backgroundColor: &#39;red&#39;,
},{
label: &#39;down&#39;,
axis: &#39;y&#39;,
data: [d2],
backgroundColor: &#39;yellow&#39;,
},{
label: &#39;uppsy&#39;,
axis: &#39;y&#39;,
data: [d22],
backgroundColor: &#39;green&#39;,
},{
label: &#39;uppsy1&#39;,
axis: &#39;y&#39;,
data: [d23],
backgroundColor: &#39;red&#39;,
},{
label: &#39;out&#39;,
axis: &#39;y&#39;,
data: [d3],
backgroundColor: &#39;yellow&#39;,
},{
label: &#39;up&#39;,
axis: &#39;y&#39;,
data: [d4],
backgroundColor: &#39;red&#39;,
}
]
};
const config = {
data,
type: &#39;bar&#39;,
options:{
plugins: {
tooltip: {
mode: &#39;dataset&#39;,
callbacks: {
label: function(item){
return moment().startOf(&#39;day&#39;).add({ minute: item.raw}).format(&#39;HH:mm&#39;);
}
}
},
legend: {
display: false,
},
title: {
display: false,
},
},
indexAxis: &#39;y&#39;,
responsive: true,
maintainAspectRatio: false,
scales: {
x: {
min: d0,
border: { display: false },
ticks: {
source: &#39;auto&#39;,
maxRotation: 80,
minRotation: 60,
autoSkip: false, 
callback: function(value, index, ticks) {
let minDiff = 30;
if(index &gt; 0 &amp;&amp; value - ticks[index-1].value &lt; minDiff){
console.info(ticks[index-1].value  - value )
return null;
}
return moment().startOf(&#39;day&#39;).add({ minute: value}).format(&#39;HH:mm&#39;);
}
},
afterBuildTicks: axis =&gt; axis.ticks = values.map(v =&gt; ({ value: v }))
},
y: {
stacked: true,
grid: { display: false },
},
}
}};
new Chart(document.getElementById(&quot;chart&quot;), config);

<!-- language: lang-html -->

&lt;script src=&quot;//cdn.jsdelivr.net/npm/chart.js&quot;&gt;&lt;/script&gt;    
&lt;script src=&quot;//cdn.jsdelivr.net/npm/moment@^2&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;//cdn.jsdelivr.net/npm/chartjs-adapter-moment@^1&quot;&gt;&lt;/script&gt;   
&lt;div class=&quot;chart&quot; style=&quot;height:84px; width:350px;&quot;&gt;
&lt;canvas  id=&quot;chart&quot; &gt;&lt;/canvas&gt;
&lt;/div&gt;

<!-- end snippet -->

Update -maybe better solution:

You could filter the possible ticks before drawing the ticks, this makes it easier to see, if the minDiff is applied in the correct manner.

values = values.reduce( (pre, curr, index) =&gt; {
if(index == 0 || (curr - pre[pre.length-1] &gt; minDiff )){
pre.push(curr);
} 
return pre;
}, [])

Here the full working demo:
<!-- begin snippet: js hide: false console: false babel: false -->

<!-- language: lang-js -->

const d0 = moment.duration(&#39;08:50:00&#39;).asMinutes();
const d1 = moment.duration(&#39;09:00:00&#39;).asMinutes();
const d2 = moment.duration(&#39;10:45:00&#39;).asMinutes();
const d22 = moment.duration(&#39;11:00:00&#39;).asMinutes();
const d23 = moment.duration(&#39;11:29:00&#39;).asMinutes();
const d3 = moment.duration(&#39;17:35:00&#39;).asMinutes();
const d4 = moment.duration(&#39;19:00:00&#39;).asMinutes();
let minDiff = 30;
let values = [d0, d1, d2, d22, d23, d3, d4];
/* prepare the ticks */
values = values.reduce( (pre, curr, index) =&gt; {
if(index == 0 || (curr - pre[pre.length-1] &gt; minDiff )){
pre.push(curr);
} 
return pre;
}, [])
let data = {
labels: [&#39;&#39;],
datasets: [{
label: &#39;up&#39;,
axis: &#39;y&#39;,
data: [d1],
backgroundColor: &#39;red&#39;,
},{
label: &#39;down&#39;,
axis: &#39;y&#39;,
data: [d2],
backgroundColor: &#39;yellow&#39;,
},{
label: &#39;uppsy&#39;,
axis: &#39;y&#39;,
data: [d22],
backgroundColor: &#39;green&#39;,
},{
label: &#39;uppsy1&#39;,
axis: &#39;y&#39;,
data: [d23],
backgroundColor: &#39;red&#39;,
},{
label: &#39;out&#39;,
axis: &#39;y&#39;,
data: [d3],
backgroundColor: &#39;yellow&#39;,
},{
label: &#39;up&#39;,
axis: &#39;y&#39;,
data: [d4],
backgroundColor: &#39;red&#39;,
}
]
};
const config = {
data,
type: &#39;bar&#39;,
options:{
plugins: {
tooltip: {
mode: &#39;dataset&#39;,
callbacks: {
label: function(item){
return moment().startOf(&#39;day&#39;).add({ minute: item.raw}).format(&#39;HH:mm&#39;);
}
}
},
legend: {
display: false,
},
title: {
display: false,
},
},
indexAxis: &#39;y&#39;,
responsive: true,
maintainAspectRatio: false,
scales: {
x: {
min: d0,
border: { display: false },
ticks: {
source: &#39;auto&#39;,
maxRotation: 80,
minRotation: 60,
autoSkip: false, 
callback: function(value, index, ticks) {
return moment().startOf(&#39;day&#39;).add({ minute: value}).format(&#39;HH:mm&#39;);
}
},
afterBuildTicks: axis =&gt; axis.ticks = values.map(v =&gt; ({ value: v }))
},
y: {
stacked: true,
grid: { display: false },
},
}
}};
new Chart(document.getElementById(&quot;chart&quot;), config);

<!-- language: lang-html -->

&lt;script src=&quot;//cdn.jsdelivr.net/npm/chart.js&quot;&gt;&lt;/script&gt;    
&lt;script src=&quot;//cdn.jsdelivr.net/npm/moment@^2&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;//cdn.jsdelivr.net/npm/chartjs-adapter-moment@^1&quot;&gt;&lt;/script&gt;   
&lt;div class=&quot;chart&quot; style=&quot;height:84px; width:350px;&quot;&gt;
&lt;canvas  id=&quot;chart&quot; &gt;&lt;/canvas&gt;
&lt;/div&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年2月16日 15:40:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/75469140.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定