Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show different stroke in same line in rechart?

I am using recharts with react, and I need suggestion as to how I can use different strokes in the same Line in a LineChart. For example, it can show a solid line till current date, and a dashed line for a future date (think as the prediction of some data).

like image 422
xploreraj Avatar asked Aug 07 '19 08:08

xploreraj


1 Answers

I have approached problem same as @fjcero did, I was also struggling with the same problem. but since the link is no longer working, created a new fiddle.

I structed Data like below, so when we don't need a line for prediction or current simply use a null and at the intersection on data[2] the prediction and current are same variables.

    const data = [
      {month: "Feb", historical:4, current: 5, prediction:null},
      {month: "Mar", historical:11, current: 10.5, prediction:null},
      {month: "April", historical:12, current: 11, prediction:11},
      {month:"June", historical:13, current:null, prediction:13},
      {month:"July", historical:14, current:null, prediction:15},
      {month:"August", historical:15, current:null, prediction:17}
];

And than used three Line components to draw line for current, historical and prediction with one for prediction having a prop strokeDasharray="3 3" for dashed line.

Here is the link to fiddle : https://jsfiddle.net/jassMarok/q6gLxoz4/

// JS Source Only
const {LineChart, Area, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ReferenceLine, ComposedChart} = Recharts;
const data = [
      {month: "Feb", historical:4, current: 5, prediction:null},
      {month: "Mar", historical:11, current: 10.5, prediction:null},
 		  {month: "April", historical:12, current: 11, prediction:11},
      {month:"June", historical:13, current:null, prediction:13},
      {month:"July", historical:14, current:null, prediction:15},
      {month:"August", historical:15, current:null, prediction:17}
];
const SimpleLineChart = React.createClass({
	render () {
  	return (
    	<ComposedChart width={600} height={300} data={data}
            margin={{top: 5, right: 30, left: 20, bottom: 5}}>
       <XAxis dataKey="month" />
       <YAxis />
       <CartesianGrid strokeDasharray="3 3"/>
       <Tooltip/>
       <ReferenceLine y={15} label="Target Seats" stroke="red" />
       <Area type="monotone" dataKey="current" fill="#8884d8" stroke="#8884d8" />
       <Line type="monotone" dataKey="historical" stroke="#82ca9d" />
       <Line type="monotone" dataKey="prediction" stroke="#8884d8" strokeDasharray="3 3" />
      </ComposedChart>
    );
  }
})
like image 151
Jaspal Avatar answered Nov 20 '22 05:11

Jaspal