reactjs 添加新图表类型以响应数据透视表

lp0sw83n  于 2022-12-03  发布在  React
关注(0)|答案(2)|浏览(207)

我想知道是否有可能向React库plotly/react-pivotable https://github.com/plotly/react-pivottable添加新类型的图表,如雷达图。
我想添加一个蜘蛛图,总是从图表库情节,但我不知道从哪里开始,因为文档是一个小穷人和GitHub的repo是相当沉默...
也许根本不可能。
有人知道这可能吗?

ddrv8njm

ddrv8njm1#

是的,完全可以添加自定义图表。您需要从原始存储库中复制makeRenderer函数,并根据图表类型对其进行自定义。
要将新图表类型(雷达图)添加到React Pivotable,必须直接在PlotlyRenderer上添加。
下面是一个如何将雷达图添加到React Pivotable的示例:

const Plot = createPlotlyComponent(window.Plotly);
const PlotlyRenderers = createPlotlyRenderers(Plot);

const makeRenderer = (
  PlotlyComponent,
  traceOptions = {},
  layoutOptions = {},
  transpose = false
) {
  class Renderer extends React.PureComponent {
    render() {
      const pivotData = new PivotData(this.props);
      const rowKeys = pivotData.getRowKeys();
      const colKeys = pivotData.getColKeys();
      const traceKeys = transpose ? colKeys : rowKeys;
      if (traceKeys.length === 0) {
        traceKeys.push([]);
      }
      const datumKeys = transpose ? rowKeys : colKeys;
      if (datumKeys.length === 0) {
        datumKeys.push([]);
      }

      let fullAggName = this.props.aggregatorName;
      const numInputs =
        this.props.aggregators[fullAggName]([])().numInputs || 0;
      if (numInputs !== 0) {
        fullAggName += ` of ${this.props.vals.slice(0, numInputs).join(", ")}`;
      }

      const data = traceKeys.map((traceKey) => {
        const r = [];
        const theta = [];
        for (const datumKey of datumKeys) {
          const val = parseFloat(
            pivotData
              .getAggregator(
                transpose ? datumKey : traceKey,
                transpose ? traceKey : datumKey
              )
              .value()
          );
          r.push(isFinite(val) ? val : null);
          theta.push(datumKey.join("-") || " ");
        }
        const trace = { name: traceKey.join("-") || fullAggName };

        trace.fill = "toself";
        trace.r = r;
        trace.theta = theta.length > 1 ? theta : [fullAggName];

        return Object.assign(trace, traceOptions);
      });

      const layout = {
        polar: {
          radialaxis: {
            visible: true,
            range: [0, 50]
          }
        },
        /* eslint-disable no-magic-numbers */
        // width: window.innerWidth / 1.5,
        // height: window.innerHeight / 1.4 - 50
        // /* eslint-enable no-magic-numbers */
      };

      return (
        <PlotlyComponent
          data={data}
          layout={Object.assign(
            layout,
            layoutOptions,
            this.props.plotlyOptions
          )}
          config={this.props.plotlyConfig}
          onUpdate={this.props.onRendererUpdate}
        />
      );
    }
  }

  return Renderer;
}

const radarChart = () => {
  return makeRenderer(
    Plot,
    { type: "scatterpolar" },
    {},
    true
  );
}

PlotlyRenderers["Radar Chart"] = radarChart({});

const data = [
  {
    country: "Spain",
    name: "Santiago",
    surname: "Ramón y Cajal",
    sex: "Male",
    age: 57,
    subject: "Medicine"
  },
  {
    country: "United Kingdom",
    name: "Ada",
    surname: "Lovelace",
    sex: "Female",
    age: 47,
    subject: "Computing"
  },
  {
    country: "United Kingdom",
    name: "Alan",
    surname: "Turing",
    sex: "Male",
    age: 55,
    subject: "Computing"
  },
  {
    country: "France",
    name: "Antoine",
    surname: "Lavoisier",
    sex: "Male",
    age: 12,
    subject: "Chemistry"
  },
  {
    country: "Poland",
    name: "Marie",
    surname: "Curie",
    sex: "Female",
    age: 33,
    subject: "Chemistry"
  },
  {
    country: "Austria",
    name: "Hedy",
    surname: "Lamarr",
    sex: "Female",
    age: 34,
    subject: "Computing"
  },
  {
    country: "Austria",
    name: "Erwin",
    surname: "Schrödinger",
    sex: "Male",
    age: 38,
    subject: "Physics"
  }
];

export default function App() {
  const [opts, setOpts] = useState({});

  return (
    <div className="App">
      <PivotTableUI
        data={data}
        onChange={(e) => {
          setOpts(e);
          console.log(e);
        }}
        renderers={Object.assign({}, TableRenderers, PlotlyRenderers)}
        cols={["sex"]}
        rows={["subject", "country"]}
        rendererName="Table Heatmap"
        aggregatorName="Average"
        vals={["age"]}
        derivedAttributes={{ completeName: (el) => el.name + " " + el.surname }}
        {...opts}
      />
    </div>
  );
}

下面是完整的代码:https://codesandbox.io/s/react-pivot-table-custom-charts-2utqbt?file=/src/App.js:3511-4468

cu6pst1q

cu6pst1q2#

是的,可以向React Pivotable库中添加新的图表类型,包括雷达图。React Pivotable库构建在Pivotable库之上,Pivotable库是一个功能强大的数据聚合工具,可以生成各种不同的图表和可视化效果。它使用Plotly库来呈现图表,因此您可以在React Pivotable中使用Plotly支持的任何图表类型。包括雷达图。
若要向React Pivotable添加新的图表类型(如雷达图),可以使用pivottable对象的addRenderer方法。此方法需要两个参数:新图表类型的名称,以及使用Plotly库生成图表的函数。
下面的示例说明如何使用addRenderer方法将雷达图添加到React Pivotable:

import { pivottable } from 'react-pivottable';
import Plotly from 'plotly.js-basic-dist';

// Define a function that generates a radar chart using the
// data and configuration provided by the Pivottable library
const radarChartRenderer = (pivotData, opts) => {
  // Use the Plotly library to generate the chart
  const chartData = [{
    type: 'scatterpolar',
    r: pivotData.map(d => d.value),
    theta: pivotData

相关问题