user2128
user2128

Reputation: 640

Change bar color when a bar is clicked plotly-react.js

I have implemented a barchart using plotly-react.js. I would like to change the bar color when a bar is clicked to highlight the bar that was clicked.

render() {

    return (
      <div>
        <Plot
          data={this.prepData(timelineData)}
          name='process duration'
          onClick={(data) => console.log('> Plotly click: ', data)}
          type= {'bar'}
          layout={{ width: '1130', height: 650, xaxis: {rangeslider: {}} }}
        />
      </div>
    );
}

prepData(timelineData) {
    var x=[];
    var y=[];

    timelineData.forEach(function(datum,i) {
      x.push(moment.unix(datum.endTime).format('DD MMM'));
      y.push(datum.duration);
    });
    return [{
      type: 'bar',
      x:x,
      y:y,
    }];
  }

Where do I need to add the logic to change the color of the bar when that particular bar is clicked?

Upvotes: 1

Views: 2151

Answers (1)

simbathesailor
simbathesailor

Reputation: 3687

Yes, you can get the highlighting of the bar when clicked in plotlyjs. You need to give marker attribute in the data object.

Code snippet:

const Plot = createPlotlyComponent(Plotly);
const mountNode = document.getElementById("root")
colors =['#00000','#00000','#00000']

class PlotlyBarComponent extends React.Component {
  state = {
    colors: ['#00000','#00000','#00000'],
  }
  render() {
    return (
       <Plot
    data={[
        {
          type: "bar",
          x: [1, 2, 3],
          y: [2, 5, 3],
          marker:{size:16, color:this.state.colors}
        }
      ]}
      layout={{
        width: 640,
        height: 480,
        title: "A Fancy Plot"
      }}
    onClick={(data) => {
       console.log("data", data)
      var pn='',
      tn='',
      colors=[];
  for(var i=0; i < data.points.length; i++){
    pn = data.points[i].pointNumber;
    tn = data.points[i].curveNumber;
    colors = data.points[i].data.marker.color;
  };
  colors[pn] = '#C54C82';
  this.setState({
    colors: [...colors]
  })
    }}
   />
    )
  }
}
ReactDOM.render(
  <PlotlyBarComponent />,
     document.getElementById("root")
);

Codepen link

Upvotes: 2

Related Questions