Nivo P ie Chart Not Rendering - PullRequest
       5

Nivo P ie Chart Not Rendering

0 голосов
/ 18 января 2020

Я использую библиотеку диаграмм nivo и изо всех сил пытаюсь получить мои графики p ie для рендеринга. Я действительно не понимаю, почему график p ie не отображается.

Вот мой основной код компонента для приборной панели:

import React, { useState, useEffect } from "react";
import Amplify, { Storage } from "aws-amplify";
import Paper from "@material-ui/core/Paper";
import Box from "@material-ui/core/Box";
import Grid from "@material-ui/core/Grid";
import awsmobile from "./aws-exports";
import * as d3 from "d3";
import CircularProgress from "@material-ui/core/CircularProgress";
import MyResponsivePie from "./pieConfig";
import useStyles from "./useStyles";
import AppBar from "@material-ui/core/AppBar";
import Toolbar from "@material-ui/core/Toolbar";
import IconButton from "@material-ui/core/IconButton";
import CloudDownloadIcon from "@material-ui/icons/CloudDownload";
import Typography from "@material-ui/core/Typography";

Amplify.configure(awsmobile);
Storage.configure({ level: "private" });

export default function Dashboard() {
  useEffect(() => {
    getFile();
  }, []);

  const classes = useStyles();
  const [dashboard, showDashboard] = useState(false);
  const [dashboardfile, setFile] = useState();

  const getFile = async () => {
    const url = await get_url().catch(err => getFile());
    const file = await d3.csv(url);
    if (file) {
      console.log(file);
      setFile(file);
      showDashboard(true);
    }
  };

  const get_url = () => {
    var url = Storage.get("output.csv", { level: "private" }, { expires: 60 });
    console.log(url);
    return url;
  };

  const countColumnValues = (file, column) => {
    var data_count = d3
      .nest()
      .key(function(d) {
        return d[column];
      })
      .rollup(function(leaves) {
        return leaves.length;
      })
      .entries(file);

    console.log(data_count);
    return data_count;
  };

  const generatePie = (file, column) => {
    var data = countColumnValues(file, column);
    return data;
  };

  return (
    <Box className={classes.root}>
      <AppBar position="static">
        <Toolbar>
          <IconButton
            edge="start"
            className={classes.menuButton}
            color="inherit"
          >
            <CloudDownloadIcon onClick={get_url}></CloudDownloadIcon>
          </IconButton>
          <Typography variant="h6" className={classes.title}>
            Atreides Controls NLP Dashboard
          </Typography>
        </Toolbar>
      </AppBar>
      {dashboard === false && (
        <div className={classes.circle}>
          <CircularProgress />
        </div>
      )}

      {dashboard && (
        <div className={classes.root}>
          <Grid container direction="row" space={3}>
            <Grid item xs>
              <Paper className={classes.paper}>
                <div className={classes.pie}>
                  <MyResponsivePie
                    id="contains_who_pie"
                    data={generatePie(dashboardfile, "contains_whos")}
                  />{" "}
                </div>
              </Paper>
            </Grid>
            <Grid item xs>
              <Paper className={classes.paper}>
                <div className={classes.pie}>
                  <MyResponsivePie
                    id="contains_what_pie"
                    data={generatePie(dashboardfile, "contains_whats")}
                  />
                </div>
              </Paper>
            </Grid>
            <Grid item xs>
              <Paper className={classes.paper}>
                <div className={classes.pie}>
                  <MyResponsivePie
                    id="contains_how_pie"
                    data={generatePie(dashboardfile, "contains_hows")}
                  />
                </div>
              </Paper>
            </Grid>
          </Grid>
          <Grid container direction="row" space={3}>
            <Grid item xs>
              <Paper className={classes.paper}>
                <div className={classes.pie}>
                  <MyResponsivePie
                    id="multiple_who_pie"
                    data={generatePie(dashboardfile, "multiple_whos")}
                  />
                </div>
              </Paper>
            </Grid>
            <Grid item xs>
              <Paper className={classes.paper}>
                <div className={classes.pie}>
                  <MyResponsivePie
                    id="multiple_what_pie"
                    data={generatePie(dashboardfile, "multiple_whats")}
                  />{" "}
                </div>
              </Paper>
            </Grid>
            <Grid item xs>
              <Paper className={classes.paper}>
                <div className={classes.pie}>
                  <MyResponsivePie
                    id="multiple_how_pie"
                    data={generatePie(dashboardfile, "multiple_hows")}
                  />
                </div>
              </Paper>
            </Grid>
          </Grid>
          <Grid container direction="row" space={3}>
            <Grid item xs>
              <Paper className={classes.paper}>
                <div className={classes.pie}>
                  <MyResponsivePie
                    id="risk_relevance_pie"
                    data={generatePie(
                      dashboardfile,
                      "control_relevance_to_risk"
                    )}
                  />
                </div>
              </Paper>
            </Grid>
            <Grid item xs>
              <Paper className={classes.paper}>
                <div className={classes.pie}>
                  <MyResponsivePie
                    id="automated_manual_pie"
                    data={generatePie(dashboardfile, "")}
                  />
                </div>
              </Paper>
            </Grid>
            <Grid item xs>
              <Paper className={classes.paper}>
                <div className={classes.pie}>
                  <MyResponsivePie
                    id="preventative_detective_pie"
                    data={generatePie(dashboardfile, "")}
                  />
                </div>
              </Paper>
            </Grid>
          </Grid>
        </div>
      )}
    </Box>
  );
}

Компонент диаграммы p ie настроен с использованием этого компонента, который я импортирую:

import React from "react";
import { ResponsivePie } from "@nivo/pie";

const MyResponsivePie = ({ data }) => (
  <ResponsivePie
    data={data}
    margin={{ top: 40, right: 80, bottom: 80, left: 80 }}
    startAngle={-180}
    innerRadius={0.5}
    padAngle={0.7}
    cornerRadius={3}
    colors={{ scheme: "nivo" }}
    borderWidth={1}
    borderColor={{ theme: "grid.line.stroke" }}
    radialLabelsSkipAngle={10}
    radialLabelsTextXOffset={6}
    radialLabelsTextColor="#333333"
    radialLabelsLinkOffset={0}
    radialLabelsLinkDiagonalLength={16}
    radialLabelsLinkHorizontalLength={24}
    radialLabelsLinkStrokeWidth={3}
    radialLabelsLinkColor={{ from: "color", modifiers: [] }}
    slicesLabelsSkipAngle={10}
    slicesLabelsTextColor="#333333"
    animate={true}
    motionStiffness={90}
    motionDamping={15}
    legends={[
      {
        anchor: "bottom",
        direction: "row",
        translateY: 56,
        itemWidth: 100,
        itemHeight: 18,
        itemTextColor: "#999",
        symbolSize: 18,
        symbolShape: "circle",
        effects: [
          {
            on: "hover",
            style: {
              itemTextColor: "#000"
            }
          }
        ]
      }
    ]}
  />
);

export default MyResponsivePie;

и мой файл стилей выглядит так

import { green } from "@material-ui/core/colors";
import { makeStyles } from "@material-ui/core/styles";
import { forceCenter } from "d3";

const useStyles = makeStyles(theme => ({
  root: {
    height: "100vh"
  },
  success: {
    backgroundColor: green[600]
  },
  error: {
    backgroundColor: theme.palette.error.dark
  },
  icon: {
    fontSize: 20
  },
  iconVariant: {
    opacity: 0.9,
    marginRight: theme.spacing(1)
  },
  message: {
    display: "flex",
    alignItems: "center"
  },
  image: {
    backgroundImage: "url(https://source.unsplash.com/8WFnEehJWso)",
    backgroundRepeat: "no-repeat",
    backgroundColor:
      theme.palette.type === "dark"
        ? theme.palette.grey[900]
        : theme.palette.grey[50],
    backgroundSize: "cover",
    backgroundPosition: "center"
  },
  paper: {
    margin: theme.spacing(1.5, 3),
    display: "flex",
    flexDirection: "column",
    alignItems: "center"
  },
  form: {
    width: "100%", // Fix IE 11 issue.
    marginTop: theme.spacing(1)
  },
  submit: {
    margin: theme.spacing(3, 0, 2)
  },
  card: {
    maxWidth: 600
  },
  media: {
    height: 500
  },
  circle: {
    display: "flex",
    "& > * + *": {
      marginLeft: theme.spacing(2)
    }
  },
  menuButton: {
    marginRight: theme.spacing(2)
  },
  title: {
    flexGrow: 1,
    alignContent: "center"
  },
  pie: {
    height: 250
  }
}));

export default useStyles;

И, наконец, пример моих данных, возвращаемых из функции generate p ie, выглядит следующим образом:

[
{key: "True", value: 7981},
{key: "False", value: 950}
]

1 Ответ

0 голосов
/ 12 марта 2020

Проблема была довольно глупой, объект контейнера не имел указанного размера.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...