Search code examples
javascriptd3.jsrickshaw

How can I set min/max of the x-axis in Rickshaw / D3?


I want to show a linear graph of time-based data for 'today'. At noon, only half of the graph would be populated as series doesn't contain more data. How can I make rickshaw display the full chart instead of just the timeframe with existing data?


Solution

  • I had the same issue and solved it by adding null data points with the desired minimum and maximum x-value:

    <div id="chart"></div>
    <div id="x_axis"></div>
    <script>
    var graph = new Rickshaw.Graph( {
        element: document.getElementById('chart'), 
        width: 500,
        height: 200,
        renderer: 'line',
        series: [
            {   data: [         
                    { x: -5, y: null},
                    { x: 10, y: null},
                ]
            },   
            {   color: 'steelblue',         
                data: [
                    { x: 0, y: 40 },
                    { x: 1, y: 49 },
                    { x: 2, y: 38 },
                    { x: 3, y: 30 },
                    { x: 4, y: 32 } ]
            }
        ]    
    });  
    
    var x_ticks = new Rickshaw.Graph.Axis.X({
        graph: graph,
        orientation: 'bottom',
        element: document.getElementById('x_axis'),
        pixelsPerTick: 100,
    });
    
    graph.render();
    </script>
    

    This shows a graph with an x-axis from -5 to 10, with data only between 0 and 4.