Multi-colored Bar Chart with ZedGraph

From IronPython Cookbook

Revision as of 20:16, 16 June 2007 by MichaelFoord (Talk | contribs)
(diff) ← Older revision | Current revision (diff) | Newer revision → (diff)

ZedGraph is a powerful and attractive charting library. It provides a Windows Forms control and a web control, but this example produces an image file directly.

You'll need the zedgraph.dll, which you can download it from the sourceforge project.

Although the samples are generally focussed on using a Windows Forms control, adapting them to produce images instead is easy. This sample produces multi-colored bars (using a four color gradient fill):

import clr

from ZedGraph import GraphPane, PointPairList, Fill, FillType
from System.Drawing import Bitmap, Color, Graphics, RectangleF
from System.Drawing.Imaging import ImageFormat

from System import Array, Math, Random

title = "Multi-Colored Bar Chart"
xAxisTitle = "Bar Number"
yAxisTitle = "Value"
pane = GraphPane(RectangleF(0, 0, 640, 480), title, xAxisTitle, yAxisTitle)

# The ZedGraph data collection class
ppl = PointPairList()

# A .NET random number generator
rand = Random()

for i in range(16):
    x = float(i + 1)
    y = rand.NextDouble() * 1000

    # The Z axis is the color, from 0.0 to 4.0
    z = i / 4.0
    ppl.Add(x, y, z)

colorList = [Color.Red, Color.Yellow, Color.Green, Color.Blue, Color.Purple]
colors = Array[Color](colorList)

curve = pane.AddBar("Multi-Colored Bars", ppl, Color.Blue)
curve.Bar.Fill = Fill(colors)
curve.Bar.Fill.Type = FillType.GradientByZ

curve.Bar.Fill.RangeMin = 0
curve.Bar.Fill.RangeMax = 4

cream = Color.FromArgb(220, 220, 255)
pane.Chart.Fill = Fill(Color.White, cream, 45)
pane.Fill = Fill(Color.White, cream, 45)

# A hack because the axis change needs a real
# image if we aren't using a control    
bm = Bitmap(1, 1)
g = Graphics.FromImage(bm)

pane.GetImage().Save('example.png', ImageFormat.Png)

Back to Contents.