Chartjs polararea刻度标签重叠

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

Chartjs polararea ticks label getting overlapped

问题

我正在使用Chart.js的polarArea图表来显示我的数据。但是我的刻度标签被颜色遮盖了。

如何稍微移动刻度标签以使它们更可见。使用深色会导致困难。我希望将它们定位如图所示:Chartjs polararea刻度标签重叠

英文:

I am using the polarArea chart from chartjs for displaying my data.
But my tick label gets overlapped by color.

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

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

var ctx = document.getElementById(&#39;myChart&#39;).getContext(&#39;2d&#39;);
    var myChart = new Chart(ctx, {
      type: &#39;polarArea&#39;,
      data: {
        labels: [&#39;Label 1&#39;, &#39;Label 2&#39;, &#39;Label 3&#39;, &#39;Label 4&#39;, &#39;Label 5&#39;],
        datasets: [{
          data: [10, 20, 30, 40, 50],
          backgroundColor: [&#39;#FF6384&#39;, &#39;#36A2EB&#39;, &#39;#FFCE56&#39;, &#39;#4BC0C0&#39;, &#39;#9966FF&#39;]
        }]
      },
      options: {
	  maintainAspectRatio: false,
        scale: {
          pointLabels: {
            fontSize: 14,
            fontColor: &#39;black&#39;,
            fontStyle: &#39;normal&#39;,
            fontFamily: &#39;Helvetica Neue,Helvetica,Arial,sans-serif&#39;,
            callback: function(value, index, values) {
              return value + &#39;&#176;&#39;; // Add a degree symbol to the tick labels
            }
          }
        },
        plugins: [{
          afterUpdate: function(chart) {
            var ticks = chart.scales.r.ticks; // Get the tick values from the r scale
            var pointLabels = chart.scales.r.pointLabels; // Get the point labels from the r scale
            var radius = chart.scales.r.getDistanceFromCenterForValue(ticks[ticks.length-1]); // Get the radius of the outermost tick
            var offset = 50; // Set the desired offset value

            for (var i = 0; i &lt; pointLabels.length; i++) {
              var angleRadians = chart.config.options.scale.angleLines.lineWidth * i;
              var x = radius * Math.cos(angleRadians) + offset;
              var y = radius * Math.sin(angleRadians) + offset;
              pointLabels[i].x = x;
              pointLabels[i].y = y;
            }
          }
        }],
        // other chart configurations...
      }
    });

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

&lt;script src=&quot;https://cdn.jsdelivr.net/npm/chart.js&quot;&gt;&lt;/script&gt;
&lt;canvas id=&quot;myChart&quot; width=&quot;350&quot; height=&quot;400&quot;&gt;&lt;/canvas&gt;

<!-- end snippet -->

How to move tick labels slightly to make them more visible.
Using  dark colours, which create difficulty .  
I want to position as shown in image .Chartjs polararea刻度标签重叠

答案1

得分: 1

以下是翻译好的部分:

"我搜索了所有选项,似乎没有简单的方法可以做到这一点。除了那种过于简单的方式 - 在 options.scales.r.ticks.callback 中在标签文本前面添加空格字符。

以下解决方案基于创建一个自定义轴类,继承自 RadialLinearScale,并仅覆盖其 drawLabels 方法,以在标准标签绘制操作之前将画布上下文进行翻译,然后在所有其他用途中恢复它。我认为这些方法没有记录,但可以在 charts.js 的高质量源代码中轻松识别。

我还调整了一些原始选项对象键,以在此环境中使用。

class TranslatedLabelsScale extends Chart.RadialLinearScale{
    static id = 'linearRadialWithLabelTranslations';
    drawLabels(){
        const translation = this.options.ticks?.labelTranslation || {};
        this.ctx.save();
        this.ctx.translate(translation.x || 0, translation.y || 0);
        super.drawLabels();
        this.ctx.restore();
    }
}
Chart.register(TranslatedLabelsScale);

var ctx = document.getElementById('myChart').getContext('2d');
new Chart(ctx, {
    type: 'polarArea',
    data: {
        labels: ['Label 1', 'Label 2', 'Label 3', 'Label 4', 'Label 5'],
        datasets: [{
            data: [10, 20, 30, 40, 50],
            backgroundColor: ['#FF6384', '#36A2EB', '#FFCE56', '#4BC0C0', '#9966FF']
        }]
    },
    options: {
        maintainAspectRatio: false,
        scales: {
            r: {
                type: 'linearRadialWithLabelTranslations',
                ticks: {
                    padding: 10,
                    fontSize: 14,
                    color: '#000',
                    fontStyle: 'normal',
                    labelTranslation: {x: 20, y: 0},
                    z: 10,
                    backdropColor: 'rgba(255, 255, 255, 0)',
                    fontFamily: 'Helvetica Neue,Helvetica,Arial,sans-serif',
                    callback: function(value, index, values){
                        return value + '°'; // 在刻度标签中添加度符号
                    }
                }
            }
        }
    }
});
<canvas id="myChart" width="350" height="400"></canvas>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

"

英文:

I searched all options and it appears there's no simple way to this. Except the way that is too simple - adding space characters in front of the label text in options.scales.r.ticks.callback.

The solution below is based on creating a custom axis class, deriving from RadialLinearScale and overriding only its drawLabels to translate the canvas context before the standard label drawing operation and restoring it for all other uses. I don't think these methods are documented, but can be identified quite easily in the high quality source code of charts.js

I also adjusted the option object keys for some of the original options, to work in this environment.

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

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

class TranslatedLabelsScale extends Chart.RadialLinearScale{
static id = &#39;linearRadialWithLabelTranslations&#39;;
drawLabels(){
const translation = this.options.ticks?.labelTranslation || {};
this.ctx.save();
this.ctx.translate(translation.x || 0, translation.y || 0);
super.drawLabels();
this.ctx.restore();
}
}
Chart.register(TranslatedLabelsScale);
var ctx = document.getElementById(&#39;myChart&#39;).getContext(&#39;2d&#39;);
new Chart(ctx, {
type: &#39;polarArea&#39;,
data: {
labels: [&#39;Label 1&#39;, &#39;Label 2&#39;, &#39;Label 3&#39;, &#39;Label 4&#39;, &#39;Label 5&#39;],
datasets: [{
data: [10, 20, 30, 40, 50],
backgroundColor: [&#39;#FF6384&#39;, &#39;#36A2EB&#39;, &#39;#FFCE56&#39;, &#39;#4BC0C0&#39;, &#39;#9966FF&#39;]
}]
},
options: {
maintainAspectRatio: false,
scales: {
r: {
//startAngle: 20,
type: &#39;linearRadialWithLabelTranslations&#39;,
ticks: {
padding: 10,
fontSize: 14,
color: &#39;#000&#39;,
fontStyle: &#39;normal&#39;,
labelTranslation: {x: 20, y: 0},
z: 10,
backdropColor: &#39;rgba(255, 255, 255, 0)&#39;,
fontFamily: &#39;Helvetica Neue,Helvetica,Arial,sans-serif&#39;,
callback: function(value, index, values){
// poor man&#39;s solution: return &#39;     &#39;+value + &#39;&#176;&#39;
return value + &#39;&#176;&#39;; // Add a degree symbol to the tick labels
}
}
}
}, // other chart configurations...
}
});

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

&lt;canvas id=&quot;myChart&quot; width=&quot;350&quot; height=&quot;400&quot;&gt;&lt;/canvas&gt;
&lt;script src=&quot;https://cdn.jsdelivr.net/npm/chart.js&quot;&gt;&lt;/script&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年4月10日 20:35:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/75977170.html
匿名

发表评论

匿名网友

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

确定