1# -*- coding: utf-8 -*- 2# Copyright 2011 The ChromiumOS Authors 3# Use of this source code is governed by a BSD-style license that can be 4# found in the LICENSE file. 5 6"""Module to draw column chart.""" 7 8 9class ColumnChart(object): 10 """class to draw column chart.""" 11 12 def __init__(self, title, width, height): 13 self.title = title 14 self.chart_div = "".join(t for t in title if t.isalnum()) 15 self.width = width 16 self.height = height 17 self.columns = [] 18 self.rows = [] 19 self.series = [] 20 21 def AddSeries(self, column_name, series_type, color): 22 for i in range(len(self.columns)): 23 if column_name == self.columns[i][1]: 24 self.series.append((i - 1, series_type, color)) 25 break 26 27 def AddColumn(self, name, column_type): 28 self.columns.append((column_type, name)) 29 30 def AddRow(self, row): 31 self.rows.append(row) 32 33 def GetJavascript(self): 34 res = "var data = new google.visualization.DataTable();\n" 35 for column in self.columns: 36 res += "data.addColumn('%s', '%s');\n" % column 37 res += "data.addRows(%s);\n" % len(self.rows) 38 for row in range(len(self.rows)): 39 for column in range(len(self.columns)): 40 val = self.rows[row][column] 41 if isinstance(val, str): 42 val = "'%s'" % val 43 res += "data.setValue(%s, %s, %s);\n" % (row, column, val) 44 45 series_javascript = "" 46 for series in self.series: 47 series_javascript += "%s: {type: '%s', color: '%s'}, " % series 48 49 chart_add_javascript = """ 50var chart_%s = new google.visualization.ComboChart( 51 document.getElementById('%s')); 52chart_%s.draw(data, {width: %s, height: %s, title: '%s', legend: 'none', 53 seriesType: "bars", lineWidth: 0, pointSize: 5, series: {%s}, 54 vAxis: {minValue: 0}}) 55""" 56 57 res += chart_add_javascript % ( 58 self.chart_div, 59 self.chart_div, 60 self.chart_div, 61 self.width, 62 self.height, 63 self.title, 64 series_javascript, 65 ) 66 return res 67 68 def GetDiv(self): 69 return "<div id='%s' class='chart'></div>" % self.chart_div 70