Gviz Data Table¶
Author: | Charlie Clark <https://clark-consulting.eu>_ |
---|---|
Source code: | https://foss.heptapod.net/openpyxl/gviz-data-table |
Issues: | https://foss.heptapod.net/openpyxl/gviz-data-table/-/issues |
Generated: | Jun 24, 2022 |
License: | BSD |
Version: | 2.0.0 |
Introduction¶
Gviz Data Table is a simple Python library for converting Python data types to the Google Visualization Data Table JSON format. https://developers.google.com/chart/interactive/docs/reference
The Google Visualization Library itself is a Javascript library that provides interactive charts that work in pretty much any browser. The libraries cover most use cases including tables, as well as charts, so you can have a chart and a table of the same data.
Gviz Data Table is designed primarily for use with data sources such as databases. Usage is supposed to be minimal: you provide a schema, that is a list of columns, and the rows of data. A column must have a name and Python data type. It can also have a label which will be used for display, otherwise the name will be used.
Each row is a sequence of cells. Although columns are explicit row names are always the first cell in a row. Like columns, cells can also have labels. Gviz Data Table will validate each cell to make sure that data conforms to type specified in the schema and will map Python types to their JSON equivalent but it does not coerce any data, i.e. if a column has type int and a cell’s data is a string containing numerical characters only this will still raise an exception.
Gviz Data Table handles data conversion only. You will need to add the necessary Javascript to an web page in order for any charts or table to be drawn. Tables, columns and cells can all have options which are just dictionaries. As there is no further definition of options no validation of their items occurs. Unknown items will simply be ignored.
Gviz Data Table is composed of: one container class Table
; two data
classes, Cell
and Column
and one JSON encoder. Application code should
probably only ever need to use Table and the encoder.
Usage¶
Tables can be initialised with a schema or these can be added imperatively. Once one row has been added to a table no more columns can be added. Once all the rows have been added. The table can be converted into JSON using the encoder.
Example¶
Let’s say we have data representing the names and salaries of people
Name | Salary |
---|---|
Jim | 50 |
Bob | 80 |
This could be coded in Gviz Data Table like this:
from gviz_data_table import Table table = Table() table.add_column('name', str, "Name") table.add_column('salary', int, "Salary") table.append(["Jim", 50]) table.append(["Bob", 80])
This can be encoded into JSON using the encoder:
from gviz_data_table import encode encode(table)
It can also be directly encoded
table.encode()
And also used as a static data source for asynchronous loading from Javascript
table.source()
Sample HTML Page with Chart and Table¶
import os
import sqlite3
from string import Template
from gviz_data_table import Table, encoder
def data():
folder = os.path.split(__file__)[0]
db = sqlite3.connect(os.path.join(folder, "sample.db"))
c = db.cursor()
c.execute("SELECT name, salary FROM employees")
cols = [dict(id=col[0], label=col[0].capitalize(), type=col[1])
for col in c.description]
# sqlite3 unfortunately does not provide type information
cols[0]['type'] = str
cols[1]['type'] = float
t = Table(cols)
for r in c.fetchall():
name, value = r
label = f"${value}"
t.append([name, (value, label)])
return encoder.encode(t)
template = Template("""
<html>
<head>
<script src="http://www.google.com/jsapi" type="text/javascript"></script>
</head>
<body>
<script>
google.load("visualization", "1", {packages:["corechart", "table"]});
var data = $data // our data table
google.setOnLoadCallback(drawChart);
function drawChart() {
var chart_data = new google.visualization.DataTable(data);
var chart = new google.visualization.ColumnChart(document.getElementById('chart'));
chart.draw(chart_data);
}
google.setOnLoadCallback(drawTable);
function drawTable () {
var table_data = new google.visualization.DataTable(data);
var table = new google.visualization.Table(document.getElementById('table'));
table.draw(table_data);
}
</script>
<h2>Sample Chart</h2>
<div id="chart"></div>
<h2>Sample Table</h2>
<div id="table"></div>
</body>
</html>
""")
def save():
with open("chart.html", "w") as f:
f.write(template.safe_substitute(data=data()))
if __name__ == "__main__":
save()
This produces a chart and table like this:
Sample Chart
Sample Table
API¶
gviz_data_table package¶
Google Visualisation for Python
Convert Python data structures to JSON suitable for the Google Visualisation Library
Submodules¶
gviz_data_table.cell module¶
gviz_data_table.column module¶
gviz_data_table.encoder module¶
-
class
gviz_data_table.encoder.
Encoder
(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)[source]¶ Bases:
json.encoder.JSONEncoder
JSON encoder for utility classes.
Also maps datetime/date and time objects to the relevant Google Visualization pseudo Date() constructor (month = month -1). Times are lists of [h, m, s] mapped to timeofday
-
default
(obj)[source]¶ Implement this method in a subclass such that it returns a serializable object for
o
, or calls the base implementation (to raise aTypeError
).For example, to support arbitrary iterators, you could implement default like this:
def default(self, o): try: iterable = iter(o) except TypeError: pass else: return list(iterable) # Let the base class default method raise the TypeError return JSONEncoder.default(self, o)
-
formats
= {<class 'datetime.date'>: 'Date({0}, {1}, {2})', <class 'datetime.datetime'>: 'Date({0}, {1}, {2}, {3}, {4}, {5})'}¶
-
gviz_data_table.table module¶
-
class
gviz_data_table.table.
Table
(schema=None, options=None)[source]¶ Bases:
object
Tables are two-dimensional arrays with fixed schemas.
Columns are ordered dictionaries of id, label and data type.
Rows are ordered dictionaries mirroring columns.
-
add_column
(id, type, label=None, options=None)[source]¶ Add a new column
Columns cannot be added to tables which already contain data.
-
append
(row)[source]¶ Add a row.
Rows are either sequences of values, or sequences of (value, label, options) tuples, or sequences of cell dictionaries. Dictionaries are the most flexible but also the most verbose. Tuples do not have to be complete but will be exhausted in order, i.e. you can’t have just a value and options.
-
options
¶
-
Release Notes¶
2.0.0 (2022-06-24)¶
- Python 3 release
1.0.2 (2015-06-29)¶
- Support
long
type in Python 2
1.0.1 (2013-03-18)¶
- Correct release
1.0.0 (2013-03-18)¶
- Python 3 compatibile
- Changed convenience import:
encode
replacesencoder
- Added convenience methods to Table to allow direct encoding as JSON and a Google data source.
0.9.1 (2012-07-26)¶
- Changed signature of add_column when I found I used it wrongly myself in the docs
0.9 (2012-07-25)¶
- Initial release