Google Visualization折线图,对数显示,数据值为0

时间:2013-12-19 09:56:35

标签: javascript google-visualization

创建Google Line图表时,我最近遇到了一个问题,无法在Stack Overflow上找到答案。在我从震惊中恢复并在其他地方找到答案后,我想我会在这里发布一个Q& A解决方案。

当你的系列包含0的数据时,如果你使用标准的LineGraph,一切看起来都很好:

Line graph, standard scale

(请注意,我更改了此图表的数字,因此您实际上可以看到没有对数刻度的多行。)

如果您的图表中存在大规模差异,那么一种解决方案是打开logScale。但是logScale只是完全跳过0或更低的任何值,导致图表上出现孤立的行:

Line Graph, log scale

问题是如何使用对数刻度显示折线图并包含0值。

1 个答案:

答案 0 :(得分:1)

对此的解决方案实际上非常简单,尽管我发现很多人在线推荐诸如将所有0值更改为0.001,或者甚至将实际值更改为0.001并将显示值更改为0。

有一个更简单的选项,它依赖于一个未记录的功能,但它在当前版本中完美运行。只需打开scaleType:轴的“mirrorLog”,现在它将按预期显示0个值:

enter image description here

示例的最终代码如下所示:

function drawVisualization() {

            var data = new google.visualization.DataTable();
            data.addColumn('date', 'Date');

                    data.addColumn('number', 'create');

                    data.addColumn('number', 'delete');

                    data.addColumn('number', 'modify');

                    data.addColumn('number', 'recycle');

                    data.addColumn('number', 'view');

            data.addRows([

                        [new Date(1386236040783),10477,8,28,2,2],

                        [new Date(1386322440783),13202,0,18,0,5],

                        [new Date(1386581640783),23856,0,105,0,6],

                        [new Date(1386668040783),9218,0,22,0,0],

                        [new Date(1386754440783),1441,0,14,0,0],

                        [new Date(1386840840783),832,2,7,0,0],

                        [new Date(1386927240783),240,22,41,4,4],

                        [new Date(1387186440783),2032,0,12,0,0],

                        [new Date(1387272840783),667,0,11,2,1],

                        [new Date(1387359240783),26535,50,69,11,16],

            ]);
            // Set chart options
            var options = {
                'title':'Activity over time',
                'animation.easing':'out',
                'animation.duration':1000,
                'pointSize':2,
                'vAxes': {0: {logScale: true, scaleType:"mirrorLog"}},
            };
            // Instantiate and draw our chart, passing in some options.
            var chart = new google.visualization.LineChart(document.getElementById('visualization'));
            chart.draw(data, options);  // Create and populate the data table.

 }

您可以在Google游乐场试用,只需将整个代码复制到方法中:

http://code.google.com/apis/ajax/playground/?type=visualization#line_chart

重要的部分是将scaleType打开到mirrorLog的vAx配置,不需要将logScale设置为true,尽管这样做没有坏处。

更改'vAxes': {0: {logScale: true, scaleType:"mirrorLog"}}中的选项可让您查看不同的行为。只需删除vAxes的一个或两个配置条目,即可查看图表的更改方式。

相关问题