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

ChartJS 3中Y轴标题的位置调整与旋转实现方法

ChartJS 3中Y轴标题的位置调整与旋转实现方法

嗨,我看了你提供的图表配置和需求——要把Y轴的€符号移到顶部,并且旋转成方便阅读的横向样式对吧?我完全理解看直观的图表会更清楚,不过咱们直接通过调整ChartJS的配置就能轻松实现你要的效果,下面是具体的修改方案:

你当前的Y轴标题配置只设置了align: 'end',这会让€符号默认显示在Y轴底部,而且是纵向旋转的状态。我们只需要给Y轴的title配置补充几个属性就能搞定:

修改后的Y轴核心配置

把你现有配置里的scales.y部分替换成下面这段,关键调整都标在注释里了:

y: {
  title: {
    display: true,
    text: '€',
    position: 'top', // 将标题定位到Y轴顶部
    rotation: 0, // 取消默认的90度旋转,让€横向显示
    align: 'center', // 让标题在Y轴顶部居中,也可以设为'start'靠左
    padding: { top: -10 }, // 微调内边距,避免标题和图表顶部内容拥挤,数值可按需调整
    // 可选:统一字体样式,和图表整体风格匹配
    font: {
      size: 14,
      color: getStyle('--cui-body-color')
    }
  },
  beginAtZero: true,
  border: {
    color: getStyle('--cui-border-color-translucent'),
  },
  grid: {
    color: getStyle('--cui-border-color-translucent'),
  },
  ticks: {
    color: getStyle('--cui-body-color'), // 和X轴刻度颜色保持统一
  },
},

完整的可直接使用的配置代码

这里是整合了修改后的完整chartDashboardOptions,你可以直接复制替换原有代码:

export const chartDashboardOptions = {
  animation: false,
  maintainAspectRatio: false,
  plugins: {
    legend: {
      position: 'top',
      align: 'end',
      labels: {
        boxHeight: 7,
        usePointStyle: true,
        padding: 20,
      },
    },
  },
  scales: {
    x: {
      grid: {
        color: getStyle('--cui-border-color-translucent'),
        drawOnChartArea: false,
      },
      ticks: {
        color: getStyle('--cui-body-color'),
      },
    },
    y: {
      title: {
        display: true,
        text: '€',
        position: 'top',
        rotation: 0,
        align: 'center',
        padding: { top: -10 },
        font: {
          size: 14,
          color: getStyle('--cui-body-color')
        }
      },
      beginAtZero: true,
      border: {
        color: getStyle('--cui-border-color-translucent'),
      },
      grid: {
        color: getStyle('--cui-border-color-translucent'),
      },
      ticks: {
        color: getStyle('--cui-body-color'),
      },
    },
  },
  elements: {
    line: {
      tension: 0.4,
    },
    point: {
      radius: 5,
      hitRadius: 10,
      hoverRadius: 4,
      hoverBorderWidth: 3,
    },
  },
}

简单说下关键属性的作用:

  • position: 'top':把Y轴标题从默认的底部直接移到顶部区域
  • rotation: 0:默认Y轴标题是90度纵向旋转的,设为0后€就会横向显示,阅读起来更自然
  • padding.top:因为标题移到顶部后可能会和上方的图例(legend)太近,微调这个数值可以让布局更宽松美观

如果调整后还有细节需要优化,比如标题的左右位置,你可以把align改成'start'或者'end',或者调整paddingleft属性来适配你的页面布局。

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

火山引擎 最新活动