How do I read and modify axes on an already-drawn Google chart?

后端 未结 2 742
傲寒
傲寒 2021-01-16 11:28

I have a page with several google charts on it, mostly combo charts and line charts. For instance:

chart = new google.visualization.LineChart(chartDiv);
         


        
2条回答
  •  北恋
    北恋 (楼主)
    2021-01-16 12:10

    You'd have to ask @Sjoerd how getChartLayoutInterface() works, since it doesn't seem there is any documentation online.

    In the meantime, what you can do is to get the min and max values of each chart that you're creating, and then take the max and min of the max/min for all charts combined.

    Using those max/min values, you can manually set the min/max for each chart (with some nice rounding). To do the rounding nicely, I suggest the following:

    // Take the Max/Min of all data values in all graphs
    var totalMax = 345;
    var totalMin = -123;
    
    // Figure out the largest number (positive or negative)
    var biggestNumber = Math.max(Math.abs(totalMax),Math.abs(totalMin));
    
    // Round to an exponent of 10 appropriate for the biggest number
    var roundingExp = Math.floor(Math.log(biggestNumber) / Math.LN10);
    var roundingDec = Math.pow(10,roundingExp);
    
    // Round your max and min to the nearest exponent of 10
    var newMax = Math.ceil(totalMax/roundingDec)*roundingDec;
    var newMin = Math.floor(totalMin/roundingDec)*roundingDec;
    
    // Determine the range of your values
    var range = newMax - newMin;
    
    // Define the number of gridlines (default 5)
    var gridlines = 5;
    
    // Determine an appropriate gap between gridlines
    var interval = range / (gridlines - 1);
    
    // Round that interval up to the exponent of 10
    var newInterval = Math.ceil(interval/roundingDec)*roundingDec;
    
    // Re-round your max and min to the new interval
    var finalMax = Math.ceil(totalMax/newInterval)*newInterval;
    var finalMin = Math.floor(totalMin/newInterval)*newInterval;
    

    This is similar to how Google determines max/min values (sometimes if you have, say, -6.2, and 3.1 as values, it will use 3.1 for gridlines even though it is an odd number to use). But by creating your own rounding, you can get around needing to figure out how google rounds (which is a tricky proposition).

    Let me know if you don't understand properly.

提交回复
热议问题