You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Chart.js仅显示主轴线及区分正负Y轴刻度颜色的实现方法咨询

Chart.js仅显示主轴线及区分正负Y轴刻度颜色的实现方法咨询

我最近在用Chart.js做折线图,碰到两个样式定制的问题,翻了不少资料都没找到精准的解决办法,想请教下各位大佬:

我的两个核心需求

  • 网格线样式区分:希望只把**x轴(y=0的基线)y轴(x=0的基线)**这两条主轴线用特殊样式(就像我图里圈出来的绿色线那样),其他普通网格线保持现有样式就行。
  • Y轴刻度颜色区分:Y轴的刻度值,想给负数标成红色,正数标成灰色,对应图里黄圈里的那些数字。

我已经做过的尝试

  • 问过ChatGPT,但给出的回答既不清晰也没精准对应我的问题,我甚至怀疑是不是自己提问的方式不对;
  • 也查过Chart.js的轴样式官方文档和相关问题讨论,但还是没找到适配的方案;

我的当前配置代码

const settings =  {
      type: 'line', // Line chart
      data: getEmptyChartData(), // Datasets settings
      options: {
          responsive: true,
          plugins: {
            legend: {
              display: true,
              position: "top",
              labels: {
                  font:{size: "19rem", weight: 'italic', padding: 10},
                  color: chartTextColr, // Legend text color
              },
          },
              zoom: {
                  pan: {
                      enabled: true,  // Enable panning
                      mode: 'xy',  // Enable panning in both directions
                      threshold: 0,  // Allow immediate panning
                      rangeMin: {
                        x: 0 // Prevents panning to negative X
                      }
                  },
                  zoom: {
                      wheel: {
                          enabled: true,  // Enable zooming with mouse wheel
                      },
                      mode: 'xy',  // Enable zooming in both directions
                  },
                  decimation: {
                    enabled: true,
                    algorithm: 'lttb',
                    samples: 20 // Number of data points to keep after zooming
                }
              },
          },
          scales: {
            x: {
                type: 'linear', // Specify linear X-axis
                position: 'bottom',
                min: 0,
                title: {display: true, text: 'Price', color: chartTextColr, font: fontSettings},
                grid: {
                  //color: chartGridLineColor, // Regular grid lines color
                  color: "red", // Regular grid lines color
                  borderColor: 'red', // X-axis (y = 0) line emphasized
                  borderWidth: 2,
                  tickColor: "green"
                },
                ticks: {color: chartTicksColor, 
                        major: {enable: true, color: "blue"}},
            },
            y: {
                title: {display: true, text: 'PnL', color: chartTextColr, font: fontSettings},
                grid: {color: chartGridLineColor },
                ticks: {color: chartTicksColor},               
            },
        },
      }
  };

效果参考示意图

chart current format
(图里绿色圈出的是我要改样式的主轴线,黄色圈出的是要区分颜色的Y轴刻度数字)

备注:内容来源于stack exchange,提问作者OJNSim

火山引擎 最新活动