首页 > 解决方案 > 垂直条形图上的 Chart.js x 轴标签镜像

问题描述

Chart.js 不支持垂直“条形”图表上的“镜像”选项。我试图寻找解决方法,但在互联网上没有找到任何帮助。

我写了一个解决方案,但只有一件事要解决才能成为完美的镜像:

实际文本对齐

有人可以帮我解决这个问题吗?

var ctx = document.getElementById("myChart").getContext("2d");
var myChart = new Chart(ctx, {
  type: "bar",
  data: {
    labels: ["ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT"],
    datasets: [{
      label: "Quota mensile",
      backgroundColor: [
        "rgba(255, 255, 153, 1)",
        "rgba(255, 255, 153, 1)",
        "rgba(255, 255, 153, 1)",
        "rgba(255, 255, 153, 1)",
        "rgba(255, 255, 153, 1)",
        "rgba(255, 255, 153, 1)",
        "rgba(255, 255, 153, 1)",
        "rgba(255, 255, 153, 1)"
      ],
      borderColor: [
        "rgba(255, 255, 153, 1)",
        "rgba(255, 255, 153, 1)",
        "rgba(255, 255, 153, 1)",
        "rgba(255, 255, 153, 1)",
        "rgba(255, 255, 153, 1)",
        "rgba(255, 255, 153, 1)",
        "rgba(255, 255, 153, 1)",
        "rgba(255, 255, 153, 1)"
      ],
      borderWidth: 1,
      data: [10, 11, 18, 10, 13, 28, 12, 16]
    }]
  },
  options: {
    legend: {
      display: false
    },
    scales: {
      xAxes: [{
        ticks: {
          maxRotation: 90,
          minRotation: 90,
          display: "top"
        },
      }],
      yAxes: [{
        display: false
      }]
    },
    tooltips: {
      enabled: true
    },
    maintainAspectRatio: true,
    responsive: true
  }
});

Chart.plugins.register({
  /* Adjust axis labelling font size according to chart size */
  id: "responsiveXlabels",
  beforeDraw: function(c) {
    var chartHeight = c.chart.height;
    var size = (chartHeight * 2.5) / 100;
    var xAxis = c.scales["x-axis-0"];
    xAxis.options.ticks.minor.fontSize = size;
    xAxis.height = 10;
    xAxis.minSize.height = 10;
    c.options.scales.xAxes[0].ticks.padding = -size * 4.5;
    xAxis.margins.bottom = size * 12.5;
  },
  afterDraw: function(c) {
    c.options.scales.xAxes[0].ticks.padding = -158;
  }
});
<canvas id="myChart" width="800" height="600"></canvas>

responsiveXlabel 插件用于在调整大小时转换文本。

希望这对想要在 X 轴上实现镜像并满足响应请求的人有所帮助。

小提琴链接到我的解决方案:小提琴链接

我使用了一个 chart.js 2.8.0 修改版本,您可以在此链接中找到 A CodePEN BY Jukka Kurkela

标签: javascripthtmlchart.js

解决方案


推荐阅读