数据源 Python 库
使用集合让一切井井有条
根据您的偏好保存内容并对其进行分类。
Google 开源了一个 Python 库,可创建 DataTable
对象供可视化图表使用。该库可用于在 Python 中创建 DataTable
,并以下述三种格式之一输出:
- JSON 字符串 - 如果您正在托管使用您数据的可视化图表的网页,可以生成一个 JSON 字符串并传递到
DataTable
构造函数中以进行填充。
- JSON 响应 - 如果您未托管托管可视化图表的页面,只是想充当外部可视化图表的数据源,则可以创建可在响应数据请求时返回的完整 JSON 响应字符串。
- JavaScript 字符串 - 您可以将数据表输出为包含几行 JavaScript 代码的字符串,这些代码将使用 Python 表中的数据创建并填充
google.visualization.DataTable
对象。然后,您可以在引擎中运行此 JavaScript,以生成并填充 google.visualization.DataTable
对象。这通常仅用于调试。
本文档假定您了解基本的 Python 编程,并且已阅读有关
创建可视化图表和使用可视化图表的简介文档。
目录
如何使用该库
下面更详细地介绍了基本步骤:
1. 创建 gviz_api.DataTable
对象
从上面的链接导入 gviz_api.py 库,并实例化 gviz_api.DataTable
类。该类接受两个参数:表架构(用于描述表中数据的格式)和要填充表的可选数据。您可以稍后根据需要添加数据,也可以完全覆盖数据,但不能移除个别行,或者清除表架构。
2. 描述表架构
表架构由传入构造函数中的 table_description
参数指定。一旦设置便无法再进行更改。该架构描述了表中的所有列:每列的数据类型、ID 和可选标签。
每一列都由一个元组进行描述:(ID [,data_type [,label [,custom_properties]]]]。
- ID - 用于标识列的字符串 ID。可以包含空格。
每列的 ID 必须是唯一的。
- data_type - [可选] 该列中数据的 Python 数据类型的字符串描述符。您可以在 SingleValueToJS() 方法中找到受支持数据类型的列表。例如“string”和“boolean”。
如果未指定,则默认为“string”。
- label - 简单易懂的列名称,可能会作为可视化图表的一部分显示。如果未指定,则系统会使用 ID 值。
- custom_properties - 自定义列属性的 {String:String} 字典。
表架构是列描述符元组的集合。每个列表成员、字典键或字典值都必须是另一个集合或描述符元组。您可以使用字典或列表的任意组合,但每个键、值或成员最终必须计算为描述符元组。以下是一些示例。
- 列列表:[('a', 'number'), ('b', 'string')]
- Dictionary of lists: {('a', 'number'): [('b', 'number'), ('c', 'string')]}
- Dictionary of dictionaries: {('a', 'number'): {'b': 'number', 'c': 'string'}}
- 依此类推,嵌套任意级别。
3. 填充数据
如需将数据添加到表中,请构建数据元素结构,采用与表架构完全相同的结构。因此,例如,如果您的架构是列表,则数据必须是列表:
- schema: [("color", "string"), ("shape", "string")]
- 数据:[["blue", "square"], ["red", "circle"]]
如果架构是一个字典,则数据必须是字典:
- schema: {("rowname", "string"): [("color", "string"),
("shape", "string")] }
- 数据:{"row1": ["blue", "square"], "row2":
["red", "circle"]}
表中的一行是相应数据和架构的一部分。例如,以下代码段展示了如何将一个由两列构成的列表的架构应用于两行数据。
Schema:[(color),(shape)]
/ \
Data: [["blue", "square"], ["red", "circle"]]
Table:
Color Shape
blue square
red circle
请注意,此处的字典键的计算结果为列数据。您可以在代码的 AppendData() 方法文档中找到更复杂的示例。允许这种复杂嵌套的目的是让您能够使用适合自己需求的 Python 数据结构。
4. 输出数据
最常见的输出格式是 JSON,因此您可能会使用 ToJsonResponse()
函数来创建要返回的数据。但是,如果您解析输入请求并支持不同的输出格式,则可以调用任何其他输出方法以返回其他格式,包括逗号分隔值、制表符分隔值和 JavaScript。JavaScript 通常仅用于调试。请参阅实现数据源,了解如何处理请求以获得首选响应格式。
用法示例
以下是一些示例,展示了如何使用各种输出格式。
ToJSon 和 ToJS 示例
#!/usr/bin/python
import gviz_api
page_template = """
<html>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<script>
google.charts.load('current', {packages:['table']});
google.charts.setOnLoadCallback(drawTable);
function drawTable() {
%(jscode)s
var jscode_table = new google.visualization.Table(document.getElementById('table_div_jscode'));
jscode_table.draw(jscode_data, {showRowNumber: true});
var json_table = new google.visualization.Table(document.getElementById('table_div_json'));
var json_data = new google.visualization.DataTable(%(json)s, 0.6);
json_table.draw(json_data, {showRowNumber: true});
}
</script>
<body>
<H1>Table created using ToJSCode</H1>
<div id="table_div_jscode"></div>
<H1>Table created using ToJSon</H1>
<div id="table_div_json"></div>
</body>
</html>
"""
def main():
# Creating the data
description = {"name": ("string", "Name"),
"salary": ("number", "Salary"),
"full_time": ("boolean", "Full Time Employee")}
data = [{"name": "Mike", "salary": (10000, "$10,000"), "full_time": True},
{"name": "Jim", "salary": (800, "$800"), "full_time": False},
{"name": "Alice", "salary": (12500, "$12,500"), "full_time": True},
{"name": "Bob", "salary": (7000, "$7,000"), "full_time": True}]
# Loading it into gviz_api.DataTable
data_table = gviz_api.DataTable(description)
data_table.LoadData(data)
# Create a JavaScript code string.
jscode = data_table.ToJSCode("jscode_data",
columns_order=("name", "salary", "full_time"),
order_by="salary")
# Create a JSON string.
json = data_table.ToJSon(columns_order=("name", "salary", "full_time"),
order_by="salary")
# Put the JS code and JSON string into the template.
print "Content-type: text/html"
print
print page_template % vars()
if __name__ == '__main__':
main()
ToJSonResponse 示例
JSonResponse 由远程客户端在数据请求中使用。
#!/usr/bin/python
import gviz_api
description = {"name": ("string", "Name"),
"salary": ("number", "Salary"),
"full_time": ("boolean", "Full Time Employee")}
data = [{"name": "Mike", "salary": (10000, "$10,000"), "full_time": True},
{"name": "Jim", "salary": (800, "$800"), "full_time": False},
{"name": "Alice", "salary": (12500, "$12,500"), "full_time": True},
{"name": "Bob", "salary": (7000, "$7,000"), "full_time": True}]
data_table = gviz_api.DataTable(description)
data_table.LoadData(data)
print "Content-type: text/plain"
print
print data_table.ToJSonResponse(columns_order=("name", "salary", "full_time"),
order_by="salary")
如未另行说明,那么本页面中的内容已根据知识共享署名 4.0 许可获得了许可,并且代码示例已根据 Apache 2.0 许可获得了许可。有关详情,请参阅 Google 开发者网站政策。Java 是 Oracle 和/或其关联公司的注册商标。
最后更新时间 (UTC):2024-07-10。
[null,null,["最后更新时间 (UTC):2024-07-10。"],[[["\u003cp\u003eGoogle's open-sourced Python library, \u003ccode\u003egviz_api\u003c/code\u003e, enables the creation of \u003ccode\u003eDataTable\u003c/code\u003e objects for visualizations, supporting JSON string, JSON response, and JavaScript string output formats.\u003c/p\u003e\n"],["\u003cp\u003eThe library requires a table schema definition outlining the data types, IDs, and labels for each column within the \u003ccode\u003eDataTable\u003c/code\u003e.\u003c/p\u003e\n"],["\u003cp\u003eUsers populate the \u003ccode\u003eDataTable\u003c/code\u003e with data structured according to the defined schema, using lists or dictionaries for rows and columns.\u003c/p\u003e\n"],["\u003cp\u003e\u003ccode\u003egviz_api\u003c/code\u003e offers functions like \u003ccode\u003eToJsonResponse()\u003c/code\u003e to format data for visualization consumption, with JSON being the most common format.\u003c/p\u003e\n"],["\u003cp\u003eThe library facilitates data exchange between Python and Google Charts, enabling dynamic and interactive visualizations.\u003c/p\u003e\n"]]],[],null,["# Data Source Python Library\n\nGoogle has open-sourced a Python library that creates `DataTable`\nobjects for consumption by visualizations. This library can be used to create\na `DataTable` in Python, and output it in any of three formats:\n\n- **JSON string** -- If you are hosting the page that hosts the visualization that uses your data, you can generate a JSON string to pass into a `DataTable` constructor to populate it.\n- **JSON response**-- If you do not host the page that hosts the visualization, and just want to act as a data source for external visualizations, you can create a complete JSON response string that can be returned in response to a data request.\n- **JavaScript string** -- You can output the data table as a string that consists of several lines of JavaScript code that will create and populate a [google.visualization.DataTable](/chart/interactive/docs/reference#DataTable) object with the data from your Python table. You can then run this JavaScript in an engine to generate and populate the `google.visualization.DataTable` object. This is typically used for debugging only.\n\nThis document assumes that you understand basic [Python\nprogramming](http://www.python.org), and have read the introductory\nvisualization documentation for [creating a visualization](/chart/interactive/docs/quick_start) and [using\na visualization](/chart/interactive/docs). \n[The Python library is available here](https://github.com/google/google-visualization-python).\n\nContents\n--------\n\n- [How to Use the Library](#howtouse)\n - [Create a gviz_api.DataTable\n object](#createinstance)\n - [Describe your table schema](#describeschema)\n - [Populate your data](#populatedata)\n - [Output your data](#outputdata)\n- [Example Usage](#exampleusage)\n - [ToJSon and ToJS Example](#tojsonexample)\n - [ToJSonResponse Example](#tojsonresponseexample)\n\nHow to Use the Library\n----------------------\n\nHere are the basic steps, in more detail:\n\n### 1. Create\na `gviz_api.DataTable` object\n\nImport the gviz_api.py library from the link above and instantiate\nthe `gviz_api.DataTable` class. The class takes two parameters:\na table schema, which will describe the format of the data in the table, and\noptional data to populate the table with. You can add data later, if you like,\nor completely overwrite the data, but not remove individual rows, or clear\nout the table schema.\n\n### 2. Describe your table schema\n\nThe table schema is specified by the `table_description` parameter\npassed into the constructor. You cannot change it later. The schema describes\nall the columns in the table: the data type of each column, the ID, and an\noptional label.\n\nEach column is described by a tuple: (*ID* \\[*,data_type* \\[*,label*\n\\[*,custom_properties*\\]\\]\\]).\n\n- *ID* - A string ID used to identify the column. Can include spaces. The ID for each column must be unique.\n- *data_type* - \\[*optional*\\] A string descriptor of the Python data type of the data in that column. You can find a list of supported data types in the SingleValueToJS() method. Examples include \"string\" and \"boolean\". If not specified, the default is \"string.\"\n- *label* - A user-friendly name for the column, which might be displayed as part of the visualization. If not specified, the ID value is used.\n- *custom_properties* - A {String:String} dictionary of custom column properties.\n\nThe table schema is a collection of column descriptor tuples. Every list member,\ndictionary key or dictionary value must be either another collection or a descriptor\ntuple. You can use any combination of dictionaries or lists, but every key,\nvalue, or member must eventually evaluate to a descriptor tuple. Here are some\nexamples.\n\n- List of columns: \\[('a', 'number'), ('b', 'string')\\]\n- Dictionary of lists: {('a', 'number'): \\[('b', 'number'), ('c', 'string')\\]}\n- Dictionary of dictionaries: {('a', 'number'): {'b': 'number', 'c': 'string'}}\n- And so on, with any level of nesting.\n\n### 3. Populate your data\n\nTo add data to the table, build a structure of data elements in the exact\nsame structure as the table schema. So, for example, if your schema is a list,\nthe data must be a list:\n\n- schema: \\[(\"color\", \"string\"), (\"shape\", \"string\")\\]\n- data: \\[\\[\"blue\", \"square\"\\], \\[\"red\", \"circle\"\\]\\]\n\nIf the schema is a dictionary, the data must be a dictionary:\n\n- schema: {(\"rowname\", \"string\"): \\[(\"color\", \"string\"), (\"shape\", \"string\")\\] }\n- data: {\"row1\": \\[\"blue\", \"square\"\\], \"row2\": \\[\"red\", \"circle\"\\]}\n\nOne table row is a section of corresponding data and schema. For example,\nhere's how a schema of a list of two columns is applied to two rows of data. \n\n```\nSchema:[(color),(shape)]\n / \\ \nData: [[\"blue\", \"square\"], [\"red\", \"circle\"]]\n\nTable: \n Color Shape\n blue square\n red circle\n```\n\nNote that the\ndictionary keys here evaluate to column data. You can find more complex examples\nin the AppendData() method documentation in the code. The purpose of allowing\nsuch complex nesting is to let you use a Python data structure appropriate\nto your needs.\n\n### 4. Output your data\n\nThe most common output format is JSON, so you will probably use the `ToJsonResponse()`\nfunction to create the data to return. If, however, you are parsing the\ninput request and supporting different output formats, you can call any of\nthe other output methods to return other formats, including comma-separated\nvalues, tab-separated values, and JavaScript. JavaScript is typically only\nused for debugging. See\n[Implementing a Data Source](/chart/interactive/docs/dev/implementing_data_source) to learn\nhow to process a request to obtain the preferred response format.\n\nExample Usage\n-------------\n\nHere are some examples demonstrating how to use the various output formats.\n\n### ToJSon and ToJS Example\n\n```\n#!/usr/bin/python\n\nimport gviz_api\n\npage_template = \"\"\"\n\u003chtml\u003e\n \u003cscript src=\"https://www.gstatic.com/charts/loader.js\"\u003e\u003c/script\u003e\n \u003cscript\u003e\n google.charts.load('current', {packages:['table']});\n\n google.charts.setOnLoadCallback(drawTable);\n function drawTable() {\n %(jscode)s\n var jscode_table = new google.visualization.Table(document.getElementById('table_div_jscode'));\n jscode_table.draw(jscode_data, {showRowNumber: true});\n\n var json_table = new google.visualization.Table(document.getElementById('table_div_json'));\n var json_data = new google.visualization.DataTable(%(json)s, 0.6);\n json_table.draw(json_data, {showRowNumber: true});\n }\n \u003c/script\u003e\n \u003cbody\u003e\n \u003cH1\u003eTable created using ToJSCode\u003c/H1\u003e\n \u003cdiv id=\"table_div_jscode\"\u003e\u003c/div\u003e\n \u003cH1\u003eTable created using ToJSon\u003c/H1\u003e\n \u003cdiv id=\"table_div_json\"\u003e\u003c/div\u003e\n \u003c/body\u003e\n\u003c/html\u003e\n\"\"\"\n\ndef main():\n # Creating the data\n description = {\"name\": (\"string\", \"Name\"),\n \"salary\": (\"number\", \"Salary\"),\n \"full_time\": (\"boolean\", \"Full Time Employee\")}\n data = [{\"name\": \"Mike\", \"salary\": (10000, \"$10,000\"), \"full_time\": True},\n {\"name\": \"Jim\", \"salary\": (800, \"$800\"), \"full_time\": False},\n {\"name\": \"Alice\", \"salary\": (12500, \"$12,500\"), \"full_time\": True},\n {\"name\": \"Bob\", \"salary\": (7000, \"$7,000\"), \"full_time\": True}]\n\n # Loading it into gviz_api.DataTable\n data_table = gviz_api.DataTable(description)\n data_table.LoadData(data)\n\n # Create a JavaScript code string.\n jscode = data_table.ToJSCode(\"jscode_data\",\n columns_order=(\"name\", \"salary\", \"full_time\"),\n order_by=\"salary\")\n # Create a JSON string.\n json = data_table.ToJSon(columns_order=(\"name\", \"salary\", \"full_time\"),\n order_by=\"salary\")\n\n # Put the JS code and JSON string into the template.\n print \"Content-type: text/html\"\n print\n print page_template % vars()\n\n\nif __name__ == '__main__':\n main()\n```\n\n### ToJSonResponse\nExample\n\nJSonResponse is used by a remote client in a data request. \n\n```\n#!/usr/bin/python\n\nimport gviz_api\n\ndescription = {\"name\": (\"string\", \"Name\"),\n \"salary\": (\"number\", \"Salary\"),\n \"full_time\": (\"boolean\", \"Full Time Employee\")}\ndata = [{\"name\": \"Mike\", \"salary\": (10000, \"$10,000\"), \"full_time\": True},\n {\"name\": \"Jim\", \"salary\": (800, \"$800\"), \"full_time\": False},\n {\"name\": \"Alice\", \"salary\": (12500, \"$12,500\"), \"full_time\": True},\n {\"name\": \"Bob\", \"salary\": (7000, \"$7,000\"), \"full_time\": True}]\n\ndata_table = gviz_api.DataTable(description)\ndata_table.LoadData(data)\nprint \"Content-type: text/plain\"\nprint\nprint data_table.ToJSonResponse(columns_order=(\"name\", \"salary\", \"full_time\"),\n order_by=\"salary\")\n```"]]