Below is an example script that draws simple bar charts. It was the only acceptable way for me to programmatically generate charts in SPSS. There is something to note here - this solution needs three distinct scripting languages:
SpssClient.RunSyntax
call is in SPSS Command Syntax.BEGIN GPL
and END GPL
is in Graphics Production Language (GPL).1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import SpssClient
import string
import xml.etree.ElementTree as ET
SpssClient.StartClient()
print("Started.")
SpssClient.RunSyntax(r"""
GET FILE="D:\mydata.sav".
DATASET NAME mydata.
""")
def draw_chart_bars(id, column, dataset):
SpssClient.RunSyntax(string.Template(r"""
GGRAPH
/GRAPHDATASET NAME="${id}" DATASET=${dataset} VARIABLES=${column} REPORTMISSING=YES
/GRAPHSPEC SOURCE=INLINE.
BEGIN GPL
SOURCE: s=userSource(id("${id}"))
DATA: d=col(source(s), name("${column}"), unit.category())
GUIDE: axis(dim(2), gridlines())
ELEMENT: interval(position(summary.count(d)))
END GPL.
""").substitute(locals()))
def export_chart(id, filename):
OutputDoc = SpssClient.GetDesignatedOutputDoc()
OutputItems = OutputDoc.GetOutputItems()
for index in range(OutputItems.Size()):
OutputItem = OutputItems.GetItemAt(index)
if OutputItem.GetType() == SpssClient.OutputItemType.CHART:
ChartItem = OutputItem.GetSpecificType()
root = ET.fromstring(OutputItem.GetXML())
source = root.find(".//*[@id='d']")
if id == source.attrib['source']:
OutputItem.ExportToImage(filename, SpssClient.ChartExportFormat.png)
for column in ["color", "brand"]:
draw_chart_bars(column = column, dataset = "mydata", id = "mychart" + column)
export_chart(filename = "D:/" + column + ".png", id = "mychart" + column)
print("Done: " + column)
SpssClient.StopClient()
print("Finished.")
P.S. Yes, I am aware of a performance bug in export_chart
function where it parses the XMLs of each OutputItem
.