【问题标题】:D3 axis scaleTime format ReactD3 轴刻度时间格式 React
【发布时间】:2021-08-29 17:55:08
【问题描述】:

所以我有这段代码适用于格式日期:

formatDate(date){
        var aux= utcParse("%Y-%m-%dT%H:%M:%S.%LZ")(date);
        return aux;
    };

图表如下所示:

但是在 x 轴上,整个 datetime 对象被渲染。我只是想以这种格式“日/月”显示日期和月份。

这是我尝试过的:

formatDate(date){
        var aux= utcParse("%Y-%m-%dT%H:%M:%S.%LZ")(date);
        var formated = timeFormat("%d-%m")(aux);
        return formated;
    };

但是,当我这样做时,数据不会呈现。在它甚至引发错误之前。 请注意,我使用 x 的时间轴:

// Add X axis --> it is a date format
        var x = scaleTime()
        .domain(extent(data_render, function(d) { return d[0]; }))
        .range([ 0, width ]);

这是 React 组件的完整源代码。

import React, { Component } from 'react';
import { scaleLinear, scaleBand, scaleTime, scaleOrdinal } from 'd3-scale';
import { select, selectAll, pointer} from 'd3-selection';
import { line, curveMonotoneX, area } from 'd3-shape';
import { extent, max } from 'd3-array';
import { transition} from 'd3-transition';
import { axisBottom, axisLeft,axisRight } from "d3-axis";
import { timeParse, timeFormat , utcParse} from 'd3-time-format';

export default class MyLineChart extends Component {
    constructor(props)
    {
        super(props);
        this.state={"isLoaded":false, "circleHover":false};
        this.lineRef = React.createRef();
        this.formatDate=this.formatDate.bind(this);
        this.circleTooltip=this.circleTooltip.bind(this);
    }

    circleTooltip(circle){ 
            circle
            .append("text")
            .text("circle")
    }

    formatDate(date){
        var aux= utcParse("%Y-%m-%dT%H:%M:%S.%LZ")(date);
        //var formated = timeFormat("%d-%m")(aux);
        //console.log(formated);
        return aux;
        //return timeFormat("%d-%m")(utcParse("%Y-%m-%dT%H:%M:%S.%LZ")(date));
    };

    componentDidMount(){
        const node = this.lineRef.current;
        const { data, title, aggr} = this.props;
        var data_render = [];
        data.segments.forEach(
            (obj) => {
                data_render.push([this.formatDate(obj.end), obj[title][aggr]]);
            }
        )
        console.log(data_render);
        // set the dimensions and margins of the graph
        var margin = {top: 10, right: 30, bottom: 30, left: 60},
            width = 460 - margin.left - margin.right,
            height = 400 - margin.top - margin.bottom;
        
        // append the svg object to the body of the page
        var svg = select(node)
                .attr("width", width + margin.left + margin.right)
                .attr("height", height + margin.top + margin.bottom)
                .attr("transform",
                    "translate(" + margin.left + "," + margin.top + ")");
        
        // Add X axis --> it is a date format
        var x = scaleTime()
        .domain(extent(data_render, function(d) { return d[0]; }))
        .range([ 0, width ]);

        svg.append("g")
        .attr("transform", "translate(0," + height + ")")
        .call(axisBottom(x));

        // Add Y axis
        var y = scaleLinear()
            .domain([0, max(data_render, function(d) { return d[1]; })])
            .range([ height, 0 ]).nice();

        svg.append("g")
        .attr("transform", "translate("+0+",0)")
        .call(axisRight(y));
        
        //Add the area
        svg.append("path")
        .datum(data_render)
        .attr("fill", "#69b3a2")
        .attr("fill-opacity", .3)
        .attr("stroke", "none")
        .attr("d", area()
            .x(function(d) { return x(d[0]) })
            .y0( height )
            .y1(function(d) { return y(d[1]) }).curve(curveMonotoneX)
            )
        
        // Add the line
        svg.append("path")
        .datum(data_render)
        .attr("fill", "none")
        .attr("stroke", "steelblue")
        .attr("stroke-width", 1.5)
        .attr("d", line()
            .x(function(d) { return x(d[0]) })
            .y(function(d) { return y(d[1]) }).curve(curveMonotoneX)
            )

        // Add the circles
        svg.selectAll("myCircles")
        .data(data_render)
        .enter()
        .append("circle")
            .attr("fill", "red")
            .attr("stroke", "none")
            .attr("cx", function(d) { return x(d[0]) })
            .attr("cy", function(d) { return y(d[1]) })
            .attr("r", 5).style("opacity",1)

        svg.selectAll("myText")
        .data(data_render)
        .enter()
        .append("text")
        .attr("x", function(d){return x(d[0])})
        .attr("y", function(d){return y(d[1])})
        .text(function(d){return d[0]+' '+d[1]})
        .style("font-size","6px")
        .style("opacity",1);

        //Add the title
        svg.append("text")
        .attr("x", width/2)             
        .attr("y", margin.top)
        .attr("text-anchor", "middle")  
        .style("font-size", "16px")  
        .text(title);

        this.setState({...this.state, isLoaded:true})
    }

    render() {
        return (
            <div>
                <svg className="lineChart" ref={this.lineRef} />
            </div>
        );
    }
}

如何格式化轴以仅在 x 轴上显示日期和月份?

【问题讨论】:

    标签: javascript reactjs d3.js


    【解决方案1】:

    您希望data_render 中的值(例如d[0])成为Date 对象,这就是utcParse("%Y-%m-%dT%H:%M:%S.%LZ")(date) 返回的内容。

    那么对于你的轴,你想要像 d3.axisBottom(x).tickFormat(d3.timeFormat("%d-%m")) 这样的东西。

    【讨论】:

    • 谢谢!它按预期工作!顺便问一下,你知道我怎样才能让圆圈的文字出现在on_hover上,然后在on_mouse_out上消失吗?我尝试了几个在线可用的代码,但我无法做到!我最终添加了代码以在单独的函数中设置文本。我尝试在圆圈之后使用 .append("text) ,然后使用 on_hover 和其他函数来更改不透明度。但是我不知道为什么当我将 append 放在圆圈上时,文本不会出现。如果我把确切的相同的代码分别呈现文本,但附加到圆圈后,文本消失了。为什么?
    • 你能用相关代码创建一个单独的问题吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多