資料來源 Python 程式庫
透過集合功能整理內容
你可以依據偏好儲存及分類內容。
Google 提供開放原始碼的 Python 程式庫,可建立 DataTable
物件以視覺化方式使用。這個程式庫可用於在 Python 中建立 DataTable
,並以下列三種格式中的任一種輸出:
- JSON 字串 :如果您託管的網頁代管使用您資料的視覺化呈現方式,您可以產生 JSON 字串並傳遞至
DataTable
建構函式來填入資料。
- JSON 回應 :如果您未代管代管視覺化功能的網頁,而只是想做為外部視覺化的資料來源,則可以建立完整的 JSON 回應字串,這個字串可以在回應資料要求時傳回。
- JavaScript 字串:您可以將資料表輸出為包含幾行 JavaScript 程式碼的字串。這個字串會建立
google.visualization.DataTable
物件,並填入 Python 資料表中的資料。然後在引擎中執行這個 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")]
- 資料:[["藍色", "正方形"]、["紅色", "圓形"]]
如果結構定義是字典,資料必須是字典:
- schema: {("rowname", "string"): [("color", "string"),
("shape", "string")] }
- 資料:{"row1": ["blue", "square"], "row2":
["紅色", "圓形"]}
表格列是對應資料和結構定義的一部分,以下舉例說明將兩個資料欄清單的結構定義套用至兩列資料時。
Schema:[(color),(shape)]
/ \
Data: [["blue", "square"], ["red", "circle"]]
Table:
Color Shape
blue square
red circle
請注意,這裡的字典索引鍵評估的是資料欄資料。您可以在程式碼的 AttachData() 方法說明文件中,找到更複雜的範例。我們之所以允許這類複雜的巢狀結構,是為了讓您使用符合需求的 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")
除非另有註明,否則本頁面中的內容是採用創用 CC 姓名標示 4.0 授權,程式碼範例則為阿帕契 2.0 授權。詳情請參閱《Google Developers 網站政策》。Java 是 Oracle 和/或其關聯企業的註冊商標。
上次更新時間:2024-07-10 (世界標準時間)。
[null,null,["上次更新時間: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```"]]