Search code examples
javascriptjqueryd3.jssvgrickshaw

Responsive CHART svg


I'm trying to do responsive chart... i used this but its not responsive just when i refresh the page it scaled to right width... Any other ideas then i had ?

And i try to set a div with viewBox and preserveAspectRatio.. But the same result..

var graph = new Rickshaw.Graph( {
    element: document.querySelector("#chart"),
    height: 100,  
    series: [{
        color: '#1abc9c',
        data: [ 
            { x: 0, y: 50 }, 
            { x: 1, y: 50 }, 
            { x: 2, y: 40 }, 
            { x: 3, y: 40 }, 
            { x: 4, y: 30 },
            { x: 5, y: 20 },
            { x: 6, y: 0 },
            { x: 7, y: 0 } ]
    }]
});
 
graph.render();

var svg = d3.select('.chart-container').append("svg")
    .attr("width", '100%')
    .attr("height", '100%')
    .attr('viewBox','0 0 '+Math.min(width,height)+' '+Math.min(width,height))
    .attr('preserveAspectRatio','xMinYMin')
    .append("g")
    .attr("transform", "translate(" + Math.min(width,height) / 2 + "," + Math.min(width,height) / 2 + ")");
<div class="chart-container" id="chart"></div>


Solution

  • Ok thanks to Mark Sizer.. Solution is here :

    var seriesData = [ [
                { x: 0, y: 50 }, 
                { x: 1, y: 50 }, 
                { x: 2, y: 50 }, 
                { x: 3, y: 40 }, 
                { x: 4, y: 40 },
                { x: 5, y: 20 },
                { x: 6, y: 0 },
                { x: 7, y: 0 } ] ];
    var graph = new Rickshaw.Graph( {
    	element: document.getElementById("chart"),
    	renderer: 'area',
    	series: [
    		{
    			data: seriesData[0],
    			color: '#1abc9c'
    		}
    	]
    } );
    var resize = function() {
    	graph.configure({
    		width: window.innerWidth * 0,
    		height: window.innerHeight * 0.20
    	});
    	graph.render();
    }
    window.addEventListener('resize', resize); 
    resize();
    <script src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/rickshaw/1.5.1/rickshaw.js"></script>
    
    
    <div id="chart"></div>