簡體   English   中英

Chart.js 的一種常見組件,可與 React.js 一起使用不同的 y 軸

[英]One common component for Chart.js to use with different y-axis With React.js

useEffect(() => {
    let ctx = document.getElementById("LineChart");
    const blue = [2000, 2100, 2400, 2450, 3000];
    const yellow = [1800, 2150, 2550, 2800, 2000];
    const pink = [1200, 1100, 1050, 1010, 1000];

    const LineChart = new Chart(ctx, {
      type: "line",
      data: {
        labels: ["Jan", "Feb", "Mar", "Apr", "May"],

        datasets: [
          {
            data: blue,
            label: "New MRR",
            fill: false,
            lineTension: 0.5,
            backgroundColor: "#3ea5e0",
            borderColor: "#3ea5e0",
            pointBorderWidth: 1,
            pointHoverBackgroundColor: "rgba(75,192,192,1)",
            pointRadius: 1,
            pointHitRadius: 10,
          },
          {
            data: yellow,
            label: "Net New MRR",
            fill: false,
            lineTension: 0.5,
            backgroundColor: "#ad9a52",
            borderColor: "#ad9a52",
            pointBorderWidth: 1,
            pointHoverBackgroundColor: "rgba(75,192,192,1)",
            pointRadius: 1,
            pointHitRadius: 10,
          },
          {
            data: pink,
            label: "Lost MRR",
            fill: false,
            lineTension: 0.5,
            backgroundColor: "#5c3784",
            borderColor: "#5c3784",
            pointBorderWidth: 1,
            pointHoverBackgroundColor: "rgba(75,192,192,1)",
            pointRadius: 1,
            pointHitRadius: 10,
          },
        ],
      },
      options: {
        scales: {
          yAxes: [
            {
              ticks: {
                beginAtZero: false,
                callback: function (value, index, values) {
                  return "$" + value;
                },
              },
            },
          ],
        },
      },
    });

    let ctx2 = document.getElementById("BarChart");
    const BarChart = new Chart(ctx2, {
      type: "bar",
      data: data,
    });

我想創建一個具有相同 x 軸值但不同 y 軸值的通用圖表組件。我根據它們的類型有開關案例。所以我可以用它們的類型渲染圖表。是否有一種簡短的方法來創建一個通用圖表或我必須對所有這些進行編碼嗎? 因為現在我只能渲染一張折線圖。

以下是創建通用圖表組件的方法,該組件將在給定自定義數據的情況下繪制圖表。

https://codesandbox.io/s/serverless-frog-6bu2f?file=/src/App.js

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM