为ApexCharts中的x轴刻度设置一定的间隔 [英] Set a certain interval for x-axis ticks in ApexCharts

查看:138
本文介绍了为ApexCharts中的x轴刻度设置一定的间隔的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简介:

我有一个 ApexCharts 图表,其中包含来自API的数据.我正在使用一个名为finnhub的API来获取显示在图表上的股市数据.返回的数据具有价格数组和相应的时间数组,它们的间隔时间不相等(股市在特定时间关闭)(y轴上的价格和x轴上的时间).我获取的数据具有很高的分辨率,这意味着x轴上有很多标签,使其看起来非常混乱且难以辨认.我正在使用React Hooks.

I have a ApexCharts chart with data from an API. I'm using an API called finnhub to get the stock market data which is displayed on the chart. The data returned has an array of prices and a corresponding array of times, which are not at an equal interval (stock market is closed at certain times) (prices on the y-axis and time on the x-axis). The data I'm getting is quite high resolution, which means there are a LOT of labels on the x-axis, making it look really cluttered and unreadable. I'm using React Hooks.

我遇到的问题:

X轴标签靠得太近(图像)

如您所见,x轴上显示时间的标签实际上彼此靠得很近.看起来太混乱了.我要这样做,以便图表上大约只有4-5个标签,它们之间的间距均匀.

As you can see, the labels on the on the x-axis which are displaying the time, are really close together. It looks too cluttered. I want to make it so that there are only about 4-5 labels on the chart which are spaced out evenly across.

代码:

import React, { useState, useEffect } from "react";
import Chart from "react-apexcharts";
import axios from "axios";
import dayjs from "dayjs";

function StockChart() {
    const [options, setOptions] = useState({
        chart: {
            type: "area",
            height: 350,
            zoom: {
                enabled: false
            }
        },
        dataLabels: {
            enabled: false
        },
        stroke: {
            curve: "straight"
        },
        xaxis: {
            categories: [],
            labels: {
                formatter: function (val) {
                    return dayjs(val).format("DD. HH:mm");
                },
                hideOverlappingLabels: Boolean,
                rotate: 0,
                trim: false
            },
            axisTicks: {
                autoskip: true,
                maxTicksLimit: 4,
                interval: 3
            }
        },
        tooltip: {
            x: {
                format: "dd MMM yyyy"
            }
        },
        fill: {
            type: "gradient",
            gradient: {
                shadeIntensity: 1,
                opacityFrom: 0.7,
                opacityTo: 0.9,
                stops: [0, 100]
            }
        }
    });

    const [series, setSeries] = useState([
        {
            name: "Closing Price",
            data: []
        }
    ]);

    useEffect(() => {
        axios
            .get(
"https://finnhub.io/api/v1/stock/candle?symbol=AAPL&resolution=60&from=1572100000&to=1572910590"
            )
            .then(res => {
                setSeries(prev => {
                    prev[0].data = res.data.c.map(val => val);
                    return prev;
                });
                setOptions(prev => {
                    prev.xaxis.categories = res.data.t.map(time => time * 1000);
                    return prev;
                });
            })
            .catch(err => console.log(err));
    });

    // Ignore the below function and state, it's just for testing
    const [disableChart, setDisableChart] = useState(false);
    function toggleChart() {
        setDisableChart(prev => !prev);
    }

    return (
        <div className="chart-container">
            <h1 onClick={toggleChart}>my chart</h1>
            {disableChart ? null : (
                <Chart options={options} series={series} type="area" width="50%" />
            )}
        </div>
    );
}

export default StockChart;

我尝试过的事情:

我尝试弄乱ticks属性.没有效果.我尝试将其设置为 type:数字" type:"datetime" 图表,但这导致以下效果:

I've tried messing around with the ticks property. There was no effect. I've tried setting it to a type: "numeric" and type: "datetime" chart but that caused the following effect:

数据间隔不规律(图像)

x轴标签现在的间距是完美的,但是现在的问题是图表上的数据间距不是均匀的.如您所见, 5:50 5:55 之间的数据间隔非常大,与 5:55 上方的数据间隔不同.我希望图表的数据间隔在所有地方都相等,就像在第一张图片中一样.

The x-axis labels are now spaced perfectly, but the problem now is that the data on the chart isn't evenly spaced. As you can see, the data interval between 5:50 and 5:55 is very large, unlike the data interval right above 5:55. I want the data interval of the chart to be equal in all places, like in the first image.

代码:

import React, { useState, useEffect } from "react";
import Chart from "react-apexcharts";
import axios from "axios";
import dayjs from "dayjs";

function StockChart() {
    const [options, setOptions] = useState({
        chart: {
            type: "area",
            height: 350,
            zoom: {
                enabled: false
            }
        },
        dataLabels: {
            enabled: false
        },
        stroke: {
            curve: "straight"
        },
        xaxis: {
            type: "numeric",
            labels: {
                formatter: function (val) {
                    return dayjs(val).format("DD. HH:mm");
                },
                hideOverlappingLabels: Boolean,
                rotate: 0,
                trim: false
            },
            axisTicks: {
                show: true
            }
        },
        tooltip: {
            x: {
                format: "dd MMM yyyy"
            }
        },
        fill: {
            type: "gradient",
            gradient: {
                shadeIntensity: 1,
                opacityFrom: 0.7,
                opacityTo: 0.9,
                stops: [0, 100]
            }
        }
    });

    const [series, setSeries] = useState([
        {
            name: "Closing Price",
            data: []
        }
    ]);

    useEffect(() => {
        axios
            .get(
    "https://finnhub.io/api/v1/stock/candle?symbol=AAPL&resolution=60&from=1572100000&to=1572910590"
            )
            .then(res => {
                setSeries(prev => {
                    for (let i = 0; i < res.data.c.length; i++) {
                        console.log(res.data.t[i]);
                        prev[0].data[i] = [res.data.t[i], res.data.c[i]];
                    }
                    console.log(prev);
                    return prev;
                });
            })
            .catch(err => console.log(err));
    });

    // Ignore the below function and state, it's just for testing
    const [disableChart, setDisableChart] = useState(false);
    function toggleChart() {
        setDisableChart(prev => !prev);
    }

    return (
        <div className="chart-container">
            <h1 onClick={toggleChart}>my chart</h1>
            {disableChart ? null : (
                <Chart options={options} series={series} type="area" width="50%" />
            )}
        </div>
    );
}

export default StockChart;

我要实现的目标:

我希望在x轴上的数据标签类似于第二张图片中的数据标签(不要太杂乱,每个图表仅约4-5个标签),同时让图表本身看起来像第二张图片(数据更改之间的距离相等).任何帮助将不胜感激.

I want to have the data labels on the x-axis be similar to the ones like in the second picture (not too cluttered, only about 4-5 labels per chart), while having the chart itself look like the second picture (distance between data changes is equal). Any help would be greatly appreaciated.

PS:这是我的第一个StackOverflow问题,对不起,如果我做错了什么.

PS: This is my first StackOverflow question, sorry if I did something incorrectly.

推荐答案

好吧,我在vue-project中遇到了同样的问题.因此,这对我有所帮助:

Well, I faced the same problem but in vue-project. So this helped to me:

  methods: {
      onChartResize(event) {
        this.$refs.oilProductionProfile.updateOptions({
        xaxis: { tickAmount: Math.ceil(event.srcElement.innerWidth / 140) },
      });
    },
  },
  created() {
    window.addEventListener("resize", this.onChartResize);
  },
  destroyed() {
    window.removeEventListener("resize", this.onChartResize);
  },
 

我们订阅窗口事件,根据当前窗口的内部宽度重新计算tickAmount,然后调用"updateOptions".刷新轴.

We subscribing on window event, recalculating tickAmount according to current window's innerwidth, and then calling "updateOptions" to refresh axis.

这篇关于为ApexCharts中的x轴刻度设置一定的间隔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆