How can I add a legend to a Grapher graph using Scripter, where the legend entries are the X column headers?

This article contains a sample script for adding a legend to a graph in an existing Grapher plot, where each legend entry is tied to the plot's X column header.

To run this script:

  1. In Grapher, open the Grapher file containing the plot you wish to add a legend to.
  2. Copy the script below, or download the attached BAS file: NameLegendwithCells.BAS.
  3. In a Windows Explorer window, navigate to C:\Program Files\Golden Software\Grapher 12\Scripter.
  4. Double click on Scripter.exe to launch Scripter.
  5. Press Ctrl+A to select all of the existing lines then press Delete.
  6. If you copied this script, press Ctrl+V to paste it into Scripter. If you downloaded it, click File | Open, select the BAS file from your downloads directory, and click Open.
  7. Click Script | Run to run the script.


Sub Main
	Dim Grapher As Object
	Set Grapher = CreateObject("Grapher.Application")
	Grapher.Visible = True
	Set Doc1 = Grapher.Documents.Active
	i = 1
	While i < Doc1.Shapes.Count + 1
		If Doc1.Shapes.Item(i).Type = grfShapeGraph Then
			Set Graph1 = Doc1.Shapes.Item(i)
		End If
		i = i+1

	'Add legend
	Set Legend = Graph1.AddLegend(True)

	'Link each entry to specific worksheet cell
	'Loop through each plot, getting the X column
	i = 1
	While i < Graph1.Plots.Count+1
		iCol = Graph1.Plots(i).yCol
		   'Convert the column number to a letter
		   iAlpha = Int((iCol-1) / 26)
		   iRemainder = iCol - (iAlpha * 26)
		   If iAlpha > 0 Then
				ConvertToLetter = Chr(iAlpha + 64)
		   End If
		   If iRemainder > 0 Then
			   ConvertToLetter = ConvertToLetter & Chr(iRemainder + 64)
		   End If
		'Change the legend entry text to the right column and row
		Text1 = "<<@"+ConvertToLetter+"1>>"
		ConvertToLetter = ""

	'Link legend entries to worksheet
	While i < Legend.EntryCount+1
		Legend.EntryFont(i).worksheet = Graph1.Plots(1).worksheet
		i = i+1

End Sub


Updated October 28, 2016

Was this article helpful?
0 out of 0 found this helpful
Have more questions? Submit a request


Please sign in to leave a comment.