Google은 시각화에서 사용할 DataTable 객체를 만드는 Python 라이브러리를 오픈소스로 제공합니다. 이 라이브러리를 사용하면 Python에서 DataTable를 만들고 다음 세 가지 형식 중 하나로 출력할 수 있습니다.
JSON 문자열 -- 데이터를 사용하는 시각화를 호스팅하는 페이지를 호스팅하는 경우 JSON 문자열을 생성하여 DataTable 생성자에 전달하여 채울 수 있습니다.
JSON 응답 -- 시각화를 호스팅하는 페이지를 호스팅하지 않고 외부 시각화를 위한 데이터 소스 역할만 하려는 경우 데이터 요청에 대한 응답으로 반환될 수 있는 완전한 JSON 응답 문자열을 만들 수 있습니다.
자바스크립트 문자열 -- Python 테이블의 데이터로
google.visualization.DataTable 객체를 만들고 채우는 여러 줄의 자바스크립트 코드로 구성된 문자열로 데이터 테이블을 출력할 수 있습니다. 그런 다음 엔진에서 이 JavaScript를 실행하여 google.visualization.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'입니다.
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. 데이터 채우기
테이블에 데이터를 추가하려면 테이블 스키마와 똑같은 구조로 데이터 요소의 구조를 빌드합니다. 예를 들어 스키마가 목록인 경우 데이터는 목록이어야 합니다.
테이블 행 1개는 해당하는 데이터 및 스키마의 섹션입니다. 예를 들어 열이 두 개인 목록의 스키마가 두 데이터 행에 적용되는 방법은 다음과 같습니다.
Schema:[(color),(shape)]
/ \
Data: [["blue", "square"], ["red", "circle"]]
Table:
ColorShape
blue square
red circle
여기서 사전 키는 열 데이터로 평가됩니다. 코드의 AppendData() 메서드 문서에서 더 복잡한 예를 확인할 수 있습니다. 이처럼 복잡한 중첩을 허용하는 목적은 니즈에 적합한 Python 데이터 구조를 사용할 수 있도록 하는 것입니다.
4. 데이터 출력
가장 일반적인 출력 형식은 JSON이므로 ToJsonResponse() 함수를 사용하여 반환할 데이터를 만듭니다. 하지만 입력 요청을 파싱하고 다양한 출력 형식을 지원하는 경우 다른 출력 메서드를 호출하여 쉼표로 구분된 값, 탭으로 구분된 값, 자바스크립트 등 다른 형식을 반환할 수 있습니다. 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()
[[["이해하기 쉬움","easyToUnderstand","thumb-up"],["문제가 해결됨","solvedMyProblem","thumb-up"],["기타","otherUp","thumb-up"]],[["필요한 정보가 없음","missingTheInformationINeed","thumb-down"],["너무 복잡함/단계 수가 너무 많음","tooComplicatedTooManySteps","thumb-down"],["오래됨","outOfDate","thumb-down"],["번역 문제","translationIssue","thumb-down"],["샘플/코드 문제","samplesCodeIssue","thumb-down"],["기타","otherDown","thumb-down"]],["최종 업데이트: 2024-07-10(UTC)"],[[["\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```"]]