簡體   English   中英

使用D3在餅圖中添加數據

[英]Add data in pie chart using D3

我有一個使用 d3 的應用程序。

 import React, { useState } from "react"; import ReactDOM from "react-dom"; import * as d3 from "d3"; import Pie from "./PieGraph"; import "./styles.css"; function App() { const [data, setData] = useState([ { value: 25 }, { value: 59 }, { value: 77 } ]); return ( <div className="App"> <h1>Pie Chart with React & D3</h1> <div></div> <div className="piechart"> <Pie data={data} width={200} height={200} innerRadius={60} outerRadius={100} /> </div> </div> ); } const rootElement = document.getElementById("root"); ReactDOM.render(<App />, rootElement);

我想在靠近數字的圖表中添加其他數據,例如:

  • 25 個蘋果
  • 59櫻桃
  • 77輛汽車

我現在擁有的代碼在這里

問題:如何添加附近的數字,內部圖表,像我上面描述的文本?

假設您可以自己更改PieGraph.js ,我會執行以下操作:

  1. 更改Arc以接受具有valuelabel的數據

餅圖.js

const Arc = ({ data, index, createArc, colors, format }) => (
  <g key={index} className="arc">
    <path className="arc" d={createArc(data)} fill={colors(index)} />
    <text
      transform={`translate(${createArc.centroid(data)})`}
      textAnchor="middle"
      fill="white"
      fontSize="10"
    >
      // Here is the change
      {data.format !== undefined ? data.format : format(data.value)}
    </text>
  </g>
);
  1. 更改傳遞給Pie的數據

索引.js

const [data, setData] = useState([
    {
      value: 25,
      label: '25 apples',
    },
    {
      value: 59,
      label: '',
    },
    {
      value: 77
    }
  ]);

現在,第一個有 label '25 apples',第二個沒有 label而第三個有 label 77.00 ,就像之前的情況一樣。

暫無
暫無

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

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