Tuesday, August 25, 2009

PowerShell and ZedGraph – Example 3

Welcome to part three in our PowerShell/ZedGraph series. Make sure you take a look at Part 1 & Part 2 before you continue on. Before we jump into more advanced features, I thought I would demonstrate how to populate the chart with real data. Apparently some were not impressed by the Yuengling consumption example (a fictitious one at that!).

We will use the ever diligent Get-Process cmdlet for our "real" data. The end result will look something like this:


Pretty no?

The code:
#Load the zedgraph dll
$ZedGraphDll = "C:\zedgraph_dll_v5.1.5\ZedGraph.dll"
[System.Reflection.Assembly]::LoadFrom($ZedGraphDll) | out-null

# Create a WinForm to serve as a container
$global:form = new-object Windows.Forms.form
$form.Size = new-object System.Drawing.Size @(500,400)

# Create a ZedGraphControl
$zgc = new-object -typename ZedGraph.ZedGraphControl
$zgc.GraphPane.Title.Text = "Processes"
$zgc.GraphPane.XAxis.Title.Text = "Process"
$zgc.GraphPane.YAxis.Title.Text = "WS(MB)"

# Go fetch me some processes data
$WS = @{Name='WS';Expression={"{0:#}" -f ($_.WorkingSet/1KB)}}
$processes = Get-Process | where {$_.WorkingSet -gt 30MB} | Sort Name | select $WS, Name

$a = $b = @()
foreach($Process in $Processes)
{
$a+= $Process.WS
$b+= $Process.Name
}

$curve = $zgc.GraphPane.AddBar("Test",$null,$a,[System.Drawing.Color]::Red)
$zgc.GraphPane.XAxis.Type = 'Text'
$zgc.GraphPane.XAxis.Scale.FontSpec.Angle = 65
$zgc.GraphPane.XAxis.Scale.MajorStep = 1
$zgc.GraphPane.X2Axis.Scale.FontSpec.Size = 8
$zgc.GraphPane.XAxis.Scale.TextLabels = $b

# Hide the legend
$zgc.GraphPane.Legend.IsVisible = $False

# Make me pretty...
$zgc.GraphPane.Fill = New-Object ZedGraph.Fill([System.Drawing.Color]::WhiteSmoke,[System.Drawing.Color]::Lavender,0)
$zgc.GraphPane.Chart.Fill = New-Object ZedGraph.Fill([System.Drawing.Color]::FromArgb(255,255,245), [System.Drawing.Color]::FromArgb(255,255,190),90)

# Calculate the Axis Scale Ranges
$zgc.AxisChange()

# Add our graph to the form
$Form.Controls.Add($zgc)
$zgc.dock = [System.Windows.Forms.DockStyle]::Fill

# Show the form
$Form.Add_Shown({$form.Activate()})
[void]$form.showdialog()
The only difference in this example is we create and populate a couple arrays (forgive my naming conventions) and use them as our data points.

I hope I have answered some of the questions about "real" data utilization with ZedGraph.

Enjoy!

No comments: