Как отображать месяцы в метках оси X в старших графиках - PullRequest
0 голосов
/ 23 марта 2020

enter image description here ПРОБЛЕМА У меня есть данные для оси x как xAxisLabel ['16 июля', '16 октября', '17 января', «17 мая», «17 июля», «17 октября», «18 января», «18 апреля», «20 августа», «20 сентября»], длина которых может варьироваться. Мне нужно отобразить только 8 меток на оси x, какой бы ни была длина данных, т.е. интервал пропуска будет определен путем деления длины данных на 8.
Решения TRIED
Я пытался использовать tickPositioner для прохождения только 8 дат. Но почему-то это не отображается.

xAxis: {
        tickPositioner: function() {
        let dataDisplay=[]
        let xAxisLabel=['Jul 16', 'Oct 16', 'Jan 17', 'May 17', 'Jul 17', 'Oct 17', 'Jan 18', 'Apr 
        18','Aug 20','Sep 20'];
        let steps = xAxisLabel.length/8
        for(let i=0,k=0;k<8;i+=steps,k++){

            dataDisplay[k] = xAxisLabel[i]

        }
        return dataDisplay;
    },
        labels:{
            enabled:true,
            formatter: function(){
                   return this.value;
                }
                },

            },

Может кто-нибудь помочь в достижении желаемого результата? Вот такая скрипка https://jsfiddle.net/harshita_97/sd3trebz/20/

1 Ответ

2 голосов
/ 23 марта 2020

У меня есть полный пример здесь (любые вопросы, дайте мне знать).

https://jsfiddle.net/alexander_L/6p1nk73y/14/

Также здесь, во фрагменте переполнения стека:

let xAxisLabel=['Jul 16', 'Oct 16', 'Jan 17', 'May 17', 'Jul 17', 'Oct 17', 'Jan 18', 'Apr 18','Aug 20','Sep 20', 'Oct 20', 'Dec 20'];
let yAxisData = [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4];

//const newDate = new Date('Jul 1 16'); //test it parses data correctly
const myData = xAxisLabel.map((child,index) => {
	const modString = child.replace(/ /, " 1 ");
  const newDate = new Date(modString);
  const month = newDate.getMonth();
  const year = newDate.getFullYear();
  return [Date.UTC(year, month, 1),yAxisData[index]]
});

//console.log(myData)
        
Highcharts.chart('container', {
		chart: {
        type: 'spline'
    },
    title: {
        text: 'Example data'
    },
    subtitle: {
        text: 'Irregular time data in Highcharts JS'
    },
    xAxis: {
        type: 'datetime',
        dateTimeLabelFormats: { // do display the year
            month: '%b %y',
            year: '%Y'
        },
        title: {
            text: 'Date'
        },
        /*tickInterval: 1*/
        tickPixelInterval: 100
    },
    yAxis: {
        title: {
            text: 'Some Example Values'
        },
        min: 0
    },
    series: [{
        name: "my Example Data",
        data: myData     
    }],
    plotOptions: {
        series: {
            marker: {
                enabled: true
            }
        }
    },
});
<script src="https://code.highcharts.com/highcharts.js"></script>
<div id="container" style="height: 400px; width: 500px"></div>

Вывод:

enter image description here

Важно проанализировать ваши строки для реальных дат а затем добавьте их в данные в виде двумерного массива.

это делается с помощью .map(), по существу объединяя два массива вместе:

let xAxisLabel=['Jul 16', 'Oct 16', 'Jan 17', 'May 17', 'Jul 17', 'Oct 17', 'Jan 18', 'Apr 18','Aug 20','Sep 20', 'Oct 20', 'Dec 20'];
let yAxisData = [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4];

//const newDate = new Date('Jul 1 16'); //test it parses data correctly
const myData = xAxisLabel.map((child,index) => {
    const modString = child.replace(/ /, " 1 ");
    const newDate = new Date(modString);
    const month = newDate.getMonth();
    const year = newDate.getFullYear();
    return [Date.UTC(year, month, 1),yAxisData[index]]
});

По существу, давая эту структуру данных:

[
  [1467331200000, 29.9]
  [1475280000000, 71.5]
  [1483228800000, 106.4]
  [1493596800000, 129.2]
  [1498867200000, 144]
  [1506816000000, 176]
  [1514764800000, 135.6]
  [1522540800000, 148.5]
  [1596240000000, 216.4]
  [1598918400000, 194.1]
  [1601510400000, 95.6]
  [1606780800000, 54.4]
]

Также для изменения тиков:

И для изменения тиков вы можете изменить вот так (с помощью tickPixelInterval: 60 et c.):

 xAxis: {
        type: 'datetime',
        dateTimeLabelFormats: { // don't display the dummy year
            month: '%b',
            year: '%Y'
        },
        title: {
            text: 'Date'
        },
        /* tickInterval: 1 */
        tickPixelInterval: 60
    },

Тогда получим:

enter image description here

Или с tickPixelInterval: 20 получим:

enter image description here

Чтобы дополнительно изменить тики, вы можете попробовать это:

xAxis: {
        type: 'datetime',
        dateTimeLabelFormats: { // do display the year
            month: '%b %y',
            year: '%Y'
        },
        title: {
            text: 'Date'
        },
        /*tickInterval: 1*/
        tickPixelInterval: 10
    }

Тогда выходные данные также включают год в представлении месяца, например:

enter image description here

Пример:

let xAxisLabel=['Jul 16', 'Oct 16', 'Jan 17', 'May 17', 'Jul 17', 'Oct 17', 'Jan 18', 'Apr 18','Aug 20','Sep 20', 'Oct 20', 'Dec 20'];
let yAxisData = [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4];

//const newDate = new Date('Jul 1 16'); //test it parses data correctly
const myData = xAxisLabel.map((child,index) => {
	const modString = child.replace(/ /, " 1 ");
  const newDate = new Date(modString);
  const month = newDate.getMonth();
  const year = newDate.getFullYear();
  return [Date.UTC(year, month, 1),yAxisData[index]]
});

//console.log(myData)
        
Highcharts.chart('container', {
		chart: {
        type: 'spline'
    },
    title: {
        text: 'Example data'
    },
    subtitle: {
        text: 'Irregular time data in Highcharts JS'
    },
    xAxis: {
        type: 'datetime',
        dateTimeLabelFormats: { // do display the year
            month: '%b %y',
            year: '%Y'
        },
        title: {
            text: 'Date'
        },
        /*tickInterval: 1*/
        tickPixelInterval: 10
    },
    yAxis: {
        title: {
            text: 'Some Example Values'
        },
        min: 0
    },
    series: [{
        name: "my Example Data",
        data: myData     
    }],
    plotOptions: {
        series: {
            marker: {
                enabled: true
            }
        }
    },
});
<script src="https://code.highcharts.com/highcharts.js"></script>
<div id="container" style="height: 400px; width: 500px"></div>

или демонстрация в jsfiddle: https://jsfiddle.net/alexander_L/6p1nk73y/20/

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...