Aidan
Aidan

Reputation: 37

How to dynamically change the x-axis in ApexCharts to dates?

How do I dynamically change the max value of the x-axis to today's date? and the min value up to 15 weeks ago? How can change the x-axis to dynamically do this?

chart:{
    animations:{
        enabled: false,
    },
    toolbar: {
        show: false,
    },
    height:450,
    width: '100%',
    type: 'bar',
    background:'#ffffff',
    forColor: '#333'
},
series:[{
    name:'Calories',
    data:[80,81,83,85,82,89,90]
        }],
dataLabels:{
    enabled:false
},
markers: {
    size:0,
},
xaxis:{
    type: 'datetime',
      categories: [
         sevenWeeksBack,date
      ],
    // datetimeUTC:true,
    // datetimeFormatter:{
    //     year: 'yyyy',
    //     month:"Mmm",
    //     day: "dd"
    // },
    //   labels:{
    //       show:true,
    //   },
    //min: new Date(sevenWeeksBack).getTime(),
     //max: new Date().getTime(),
     //range: new Date(sevenWeeksBack).getTime(),
    // min:new Date(Date.now()-604800000),
     // tickAmount: 'dataPoints' 
},
yaxis:[{
        title:{
            text: ''
        }
}],
plotOptions:{
    bar:{
    horizontal: false
    }
},
fill:{
    colors: ['#33e400']
},
title:{
    text: 'Food Calories',
    align: 'left',
    margin: 20,
    offsetY: 20,
    style:{
        fontSize: '25px'
    }
},
tooltip: {
    enabled:false,
    x: {
        format: 'dd MMM yyyy'
      }
  },
  states: {
    hover: {
        filter: {
            type: 'none',
        }
    }
}

};

The incoming data will contain up to 90 days of worth of data (90 values). How can I display the x-axis to do dates?

This chart is intended to display up to 90 days. I have tried using momentjs to dynamically change the max and min value but with no success

Upvotes: 2

Views: 20261

Answers (1)

Oscar Schafer
Oscar Schafer

Reputation: 1525

I wouldn't mix type: 'datetime' with categories, if you're using categories you're probably better off using type: 'category'. That said, I believe there are two approaches you can take:

  1. If you've already formatted your dates and put them into the categories array and you know you'll always be receiving 90 days worth of values - then it'll format as you expect. There's a nice example of that approach here, referred to in the docs under "1). Single values". (This approach isn't working for you currently because from what I can see you only have 7 values in your series.data.)

  2. Use type: 'datetime' and drop the categories. This will allow you to format using x.min and x.max as you've tried. Caveat here is that you'll need to include the timestamp with each data point when passing to ApexCharts, so you might have to do some pre-processing. This is referred to as "3). Timeline Series" in the docs. I put together a codepen showing this approach, using both of the two timeline series formats.

Upvotes: 6

Related Questions