Multi-colored Bar Chart with ZedGraph

From IronPython Cookbook

Revision as of 20:18, 16 June 2007 by MichaelFoord (Talk | contribs)

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 five color gradient fill):

A multi-colored bar char

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)

This is adapted from this ZedGraph example.

Back to Contents.