Dan
Dan

Reputation: 789

Change Chart Width Programmatically - ApexCharts

When I change the width of the chart with updateOptions it is a different width than the initial load, even with same width value.

I am rendering a chart with these very basic initial options:

options: {
  id: "chart_id",
  chart: {
    width: "100%"
  }
}

I am rendering the chart with react-apexcharts as

<ReactApexChart options={options} series={series} type="bar" />

and then to change width I am calling

ApexCharts.exec('chart_id', 'updateOptions', newOptions);

where newOptions is the same as the original options, different width.

but even if I update the options with the same width, it shrinks the plot-series (the bars) compared to initial load.

first photo - original.

enter image description here

second photo - messed up (in photo, the chart width is the full screenshot but when setting chart width programmatically, the plot series shrinks as shown

enter image description here

Upvotes: 0

Views: 8339

Answers (3)

Jayesh karma
Jayesh karma

Reputation: 19

// Function to calculate the bar width
function calculateBarWidth(dataPoints) {
  const minimumWidth = 10; // Minimum width you want
  const calculatedWidth = Math.max(minimumWidth, minimumWidth / dataPoints);
  return `${calculatedWidth}px`;
}

code

import React from "react";
import ReactDOM from "react-dom";
import ReactApexChart from "react-apexcharts";

import "./styles.css";

// Function to calculate the bar width
function calculateBarWidth(dataPoints) {
  const minimumWidth = 10; // Minimum width you want
  const calculatedWidth = Math.max(minimumWidth, minimumWidth / dataPoints);
  return `${calculatedWidth}px`;
}

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      options: {
        plotOptions: {
          bar: {
            dataLabels: {
              position: "top",
            },
            columnWidth: calculateBarWidth(1), // Adjust the number of data points
          },
        },
        dataLabels: {
          enabled: true,
          formatter: function (val) {
            return Number(val).toLocaleString() + "€";
          },
          offsetY: -20,
          style: {
            fontSize: "12px",
            colors: ["#304758"],
          },
        },
        xaxis: {
          categories: ["Juin 2018"],
          position: "bottom",
          labels: {
            offsetY: 0,
          },
        },
        fill: {
          gradient: {
            shade: "light",
            type: "horizontal",
            shadeIntensity: 0.25,
            stops: [50, 0, 100, 100],
          },
        },
        yaxis: {
          axisBorder: {
            show: false,
          },
          axisTicks: {
            show: false,
          },
          labels: {
            show: false,
            formatter: function (val) {
              return Number(val).toLocaleString() + "€";
            },
          },
        },
        title: {
          text: "Revenus des 12 derniers mois",
          floating: true,
          offsetY: 0,
          align: "center",
          style: {
            color: "#444",
          },
        },
        chart: {
          animations: {
            enabled: false,
          },
        },
      },
      series: [
        {
          name: "Chiffre d'affaires",
          data: [8976],
        },
      ],
    };

    setTimeout(() => {
      this.setState({
        series: [
          {
            name: "Chiffre d'affaires",
            data: [67], // Adjust the data point value
          },
        ],
      });
    }, 4000);
  }

  render() {
    return (
      <div id="chart">
        <ReactApexChart
          options={this.state.options}
          series={this.state.series}
          type="bar"
          height="300"
        />
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Upvotes: 0

Dan
Dan

Reputation: 789

I finally got it fixed, and boy was it a strange fix.

One way that i was able to fix it was by not using react-apexcharts and instead switching to regular apexcharts like so

import ApexCharts from 'apexcharts';

componentDidMount() {
    new ApexCharts(document.getElementById('chart'), options);
    chart.render();
  }

render() {
  return <div id="chart" />
}

when i did that, the ApexCharts.exec('chart_id', 'updateOptions', newOptions); calls worked to change the width properly

but i really wanted to use react-apexcharts so through trial and error i found out that in order for the width to change correctly, I had to do two things:

First - I needed to change the width using the ApexCharts.exec('chart_id', 'updateOptions', newOptions); method in order for the chart to reload. Simply changing the width prop directly on the React component won't work.

Second - and this is the strange part, i needed to initialize a new ApexCharts object, even if the DOM hook passed to the creator was null. for example, at the top of my document, my 4 apex charts related lines are:

import ReactApexChart from "react-apexcharts";
import options from './chart-data.js';
import ApexCharts from 'apexcharts'
new ApexCharts(null, options);

I have no idea why i needed to do this just to get the chart width to behave properly. not just to update at all, mind you, but just to not have a mind of it's own. Any insight would be great, if anyone knows!

Upvotes: 2

junedchhipa
junedchhipa

Reputation: 5627

If you are using react-apexcharts, have you tried setting width directly into component's props?

<ReactApexChart options={options} series={series} width="300" type="bar" />

Next time, when you update the width props, it will automatically redraw to the new width.

If the above doesn't work, please post a working codesandbox demo to reproduce it on our side easily.

Upvotes: 0

Related Questions