简体   繁体   中英

React Recharts Dynamic charts - lines not sharing x-axis values

I am trying to build a chart in react with Recharts. The lines are not sharing the x-axis values and overlapping... I want the two charts to share the x-axis values like this: https://recharts.org/en-US/examples/SimpleLineChart

My data comes dynamically from an API call

Have created a sandbox here: https://codesandbox.io/s/rechart-stackoverflow-forked-lucfl?file=/src/BarGraph.js

Code:

import React, { Component } from "react";
import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  LineChart,
  Line
} from "recharts";
import _ from "underscore";

class BarGraph extends Component {
  state = {
    channels: [],
    data: []
  };
  componentDidMount() {
    let data = {
      channels: ["219180924-2", "219180924-1"],
      data: [
        { period: 10, "219180924-2": 0 },
        { period: 11, "219180924-2": 0 },
        { period: 12, "219180924-2": 0 },
        { period: 13, "219180924-2": 0 },
        { period: 14, "219180924-2": 0 },
        { period: 15, "219180924-2": 0 },
        { period: 16, "219180924-2": 0.01 },
        { period: 17, "219180924-2": 0.33 },
        { period: 18, "219180924-2": 0.14 },
        { period: 19, "219180924-2": 0.22 },
        { period: 20, "219180924-2": 0.69 },       
        { period: 10, "219180924-1": 0.12 },
        { period: 11, "219180924-1": 0.19 },
        { period: 12, "219180924-1": 0.2 },
        { period: 13, "219180924-1": 0.22 },
        { period: 14, "219180924-1": 0.29 },
        { period: 15, "219180924-1": 1.51 },
        { period: 16, "219180924-1": 0.03 },
        { period: 17, "219180924-1": 0 },
        { period: 18, "219180924-1": 0 },
        { period: 19, "219180924-1": 0 },
        { period: 20, "219180924-1": 0 }
      ]
    };
   

    this.setState({
      channels: data.channels,
      data: data.data
    });
  }

  render() {
    return (
      <LineChart
        width={600}
        height={300}
        data={this.state.data}
        margin={{ top: 5, right: 30, left: 20, bottom: 5 }}
      >
        <CartesianGrid strokeDasharray="1 " />
        <XAxis dataKey={'period'}/>
        <YAxis />
        <Tooltip />
        <Legend />
        {this.state.channels.map((channel) => (
          <Line dataKey={channel}  />
        ))}
      </LineChart>
    );
  }
}

export default BarGraph;

实际上已经解决了

<XAxis dataKey={'period'} allowDuplicatedCategory={false}/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM