Multi-colored Bar Chart with ZedGraph

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 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):



import clr clr.AddReference('ZedGraph') clr.AddReference('System.Drawing')

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)

ppl = PointPairList
 * 1) The ZedGraph data collection class

rand = Random
 * 1) A .NET random number generator

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)

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

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

This is adapted from this ZedGraph example.

Back to Contents.