1 # Copyright 2011 Google Inc. All Rights Reserved. 2 """Module to draw column chart.""" 3 4 5 class ColumnChart(object): 6 """class to draw column chart.""" 7 8 def __init__(self, title, width, height): 9 self.title = title 10 self.chart_div = filter(str.isalnum, title) 11 self.width = width 12 self.height = height 13 self.columns = [] 14 self.rows = [] 15 self.series = [] 16 17 def AddSeries(self, column_name, series_type, color): 18 for i in range(len(self.columns)): 19 if column_name == self.columns[i][1]: 20 self.series.append((i - 1, series_type, color)) 21 break 22 23 def AddColumn(self, name, column_type): 24 self.columns.append((column_type, name)) 25 26 def AddRow(self, row): 27 self.rows.append(row) 28 29 def GetJavascript(self): 30 res = 'var data = new google.visualization.DataTable();\n' 31 for column in self.columns: 32 res += "data.addColumn('%s', '%s');\n" % column 33 res += 'data.addRows(%s);\n' % len(self.rows) 34 for row in range(len(self.rows)): 35 for column in range(len(self.columns)): 36 val = self.rows[row][column] 37 if isinstance(val, str): 38 val = "'%s'" % val 39 res += 'data.setValue(%s, %s, %s);\n' % (row, column, val) 40 41 series_javascript = '' 42 for series in self.series: 43 series_javascript += "%s: {type: '%s', color: '%s'}, " % series 44 45 chart_add_javascript = """ 46 var chart_%s = new google.visualization.ComboChart( 47 document.getElementById('%s')); 48 chart_%s.draw(data, {width: %s, height: %s, title: '%s', legend: 'none', 49 seriesType: "bars", lineWidth: 0, pointSize: 5, series: {%s}, 50 vAxis: {minValue: 0}}) 51 """ 52 53 res += chart_add_javascript % (self.chart_div, self.chart_div, 54 self.chart_div, self.width, self.height, 55 self.title, series_javascript) 56 return res 57 58 def GetDiv(self): 59 return "<div id='%s' class='chart'></div>" % self.chart_div 60