0

我正在使用react-chartjs-2我正在处理的条形图。我已经绘制了数据并在相应条形上方显示值,我使用chartjs-plugin-datalabels了但它没有显示条形上方的值。

我做了以下

import React from "react";
import ReactDOM from "react-dom";
import { Bar } from "react-chartjs-2";
import 'chartjs-plugin-datalabels'

import "./styles.css";

const dataFromApi = [
  "19,250",
  "26,454",
  "36,118",
  "49,325",
  "64,190",
  "109,807"
];

const data = {
  labels: ["2019", "2020", "2021", "2022", "2023", "2024"],
  datasets: [
    {
      backgroundColor: "rgb(47,85,151)",
      hoverBackgroundColor: "rgb(47,85,151)",
      data: dataFromApi.map(value => parseInt(value, 10))
    }
  ]
};

function App() {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <Bar
        data={data}
        width={100}
        height={50}
        options={{
          plugins: {
            datalabels: {
              display: true,
              color: "black",
              align: "top",
              offset: 10,
              labels: {
                title: {
                  font: {
                    weight: "bold"
                  }
                }
              },
              formatter(value, context) {
                return `$${
                  context.chart.data.datasets[0].data[context.dataIndex]
                }k`;
              }
            }
          },
          maintainAspectRatio: false,
          legend: {
            display: false
          },
          tooltips: {
            display: false
          },
          scales: {
            xAxes: [
              {
                gridLines: {
                  display: false
                },
                barPercentage: 0.3,
                ticks: {
                  beginAtZero: true
                }
              }
            ],
            yAxes: [
              {
                display: false,
                gridLines: {
                  display: false
                },
                ticks: {
                  display: false,
                  beginAtZero: true
                }
              }
            ]
          }
        }}
      />
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

这是解决方法

https://codesandbox.io/s/ecstatic-fire-sroc0

我希望所有条形的值位置都像 2019 年条形图。

4

1 回答 1

0

用 设置标签的位置非常困难react-chartjs-2。即使它也不存在于文档中。

但是我已经应用了一些逻辑offset来获得位置。希望这会带您走上正确的道路。

offset: function(obj) {
  // Your logic will come here
  return obj.dataset.data[obj.dataIndex] / 2;
},

这是给你的演示https://codesandbox.io/s/cool-frog-93btz

我建议你使用highcharts

https://www.highcharts.com/demo/column-drilldown

希望对你有帮助!

于 2019-10-16T06:10:00.337 回答