IntroductionZedGraph is a class library, Windows Forms UserControl, and ASP web-accessible control for creating 2D line, bar, and pie graphs of arbitrary datasets. The classes provide a high degree of flexibility - almost every aspect of the graph can be user-modified. At the same time, usage of the classes is kept simple by providing default values for all of the graph attributes. The classes include code for choosing appropriate scale ranges and step sizes based on the range of data values being plotted. ZedGraph is maintained as an open-source development project on SourceForge. The site includes a project Wiki, documentation, interim (CVS) updates, and all release versions. A set of sample graphs is also available on the Wiki, complete with source code (many of the samples include C# and VB code). ZedGraph now supports both .NET 2.0 and .NET 1.1.
BackgroundThere are many graphing libraries out there, but none seemed to fit what I needed. I found MSChart too quirky, and many of the other options did not have the flexibility I needed to achieve a polished look. Of course, most of the commercial packages would do the trick, but I needed something that was free. So, ZedGraph was born. These classes will generate a variety of line, bar, or pie charts on a form or web page, given a location rectangle and some data points. ZedGraph handles 2D line/scatter graphs, horizontal/vertical bar graphs, stacked bar charts, stacked percent bar charts, error bar charts, open-high-low-close charts, Japanese candlestick charts, and pie charts - it does not yet handle 2.5D or 3D surfaces or charts. The charts can be dressed up with axis labels and titles, a legend, text labels and arrows (as shown in the example above), images, etc. The ZedGraphWiki and the online class documentation provide lots of helpful tips and descriptions. Refer to them for more details - ZedGraph has a tremendous number of options that are not documented in this tutorial. VB usersThis article uses C# exclusively for examples, however, all the code samples for the tutorial, plus other examples are available for Visual Basic, on the ZedGraphWiki Sample Graphs section. Using ZedGraph as a web controlZedGraph now includes a class derived from the Using ZedGraph as a UserControlZedGraph is accessible as a control from the control toolbox in Visual Studio .NET. To access ZedGraph, first launch Visual Studio .NET, and create a new Windows Application (Forms) project. Open the form design so that it appears in the current window. View the toolbox using the View/Toolbox menu command. Right-click inside the "General" or "Components" sub-pane of the tool box, and select the "Choose Items..." option. Click "Browse...", and navigate to the zedgraph.dll file. Once this file is added, you should see a
The above code will generate the following output: Enhancing the graphZedGraph allows you to modify the graph attributes in a wide variety of ways. Each of the parts of the graph is encapsulated in a class structure, which has modifiable properties to control the output. The following are some of the classes provided in ZedGraph (Note that these classes are XML documented. See the ZedGraph documentation for details about each class.):
The graph is modified by accessing properties in each of the above classes. For example, if you include the following lines of code in your ![]() // Change the color of the title
myPane.Title.FontSpec.FontColor = Color.Green;
// Add gridlines to the plot, and make them gray
myPane.XAxis.MajorGrid.IsVisible = true;
myPane.YAxis.MajorGrid.IsVisible = true;
myPane.XAxis.MajorGrid.Color = Color.LightGray;
myPane.YAxis.MajorGrid.Color = Color.LightGray;
// Move the legend location
myPane.Legend.Position = ZedGraph.LegendPos.Bottom;
// Make both curves thicker
myCurve.Line.Width = 2.0F;
myCurve2.Line.Width = 2.0F;
// Fill the area under the curves
myCurve.Line.Fill = new Fill( Color.White, Color.Red, 45F );
myCurve2.Line.Fill = new Fill( Color.White, Color.Blue, 45F );
// Increase the symbol sizes, and fill them with solid white
myCurve.Symbol.Size = 8.0F;
myCurve2.Symbol.Size = 8.0F;
myCurve.Symbol.Fill = new Fill( Color.White );
myCurve2.Symbol.Fill = new Fill( Color.White );
// Add a background gradient fill to the axis frame
myPane.Chart.Fill = new Fill( Color.White,
Color.FromArgb( 255, 255, 210 ), -45F );
// Add a caption and an arrow
TextObj myText = new TextObj( "Interesting\nPoint", 230F, 70F );
myText.FontSpec.FontColor = Color.Red;
myText.Location.AlignH = AlignH.Center;
myText.Location.AlignV = AlignV.Top;
myPane.GraphObjList.Add( myText );
ArrowObj myArrow = new ArrowObj( Color.Red, 12F, 230F, 70F, 280F, 55F );
myPane.GraphObjList.Add( myArrow );
The final "dressed-up" graph will look like this: Many more graph attributes can be modified, but listing them all in this article would be tedious. Please refer to the online documentation for more details. Also see the demo graphs on the Wiki for samples with code. Interesting tidbitsDrawing line graphs is no big deal, but there are some aspects of the drawing classes that proved to be interesting. The flexibility afforded by the transform matrix of the GDI+ drawing library is very cool. This allowed the same code to be employed for drawing all three of the axes. The coordinate system is transformed to accommodate the axis location and orientation. In each case, the coordinate system is translated and rotated so that the axis is oriented along the X direction and the origin is located at the left edge of the axis when facing from the label side. A few "if" exceptions were required to account for the fact that the "left" side of the X and Y2 axes is the minimum value and the "left" side of the Y axis is the maximum value. Choosing scalesRange and step sizeZedGraph is set up to automatically select appropriate scale minimum, maximum, and step size values based on the range of data values in the curves. Alternatively, you can manually set any or all of the values, and the scale picking logic will attempt to pick the appropriate values for the remaining parameters that are left in the automatic mode. The scale picking logic is based on the assumption that the most humanly palatable step sizes will be even divisors of 10. That is, step sizes should be 1, 2, or 5 times some power of 10. The heart of the scale picking logic is found in the protected double CalcStepSize( double range, double targetSteps )
{
// Calculate an initial guess at step size
double tempStep = range / targetSteps;
// Get the magnitude of the step size
double mag = Math.Floor( Math.Log10( tempStep ) );
double magPow = Math.Pow( (double) 10.0, mag );
// Calculate most significant digit of the new step size
double magMsd = ( (int) (tempStep / magPow + .5) );
// promote the MSD to either 1, 2, or 5
if ( magMsd > 5.0 )
magMsd = 10.0;
else if ( magMsd > 2.0 )
magMsd = 5.0;
else if ( magMsd > 1.0 )
magMsd = 2.0;
return magMsd * magPow;
}
The initial guess at the step size is calculated using a default number of steps named Zero leverAnother aspect of the scale selection is whether or not the scale should be extended to include the zero value. For example, if the scale range is 1 to 10, you would typically want to go ahead and start it at zero. This is accomplished with the GraceFinally, ZedGraph includes "grace" properties that allow you to include extra space on the scale range before and after the minimum and maximum data values, respectively. The reason for this is to avoid having the minimum and/or maximum data points fall right on the axes. Note that the grace values apply only to the non-ordinal axis types ( Axis typesEach axis now has a property called
Date-time axesZedGraph includes the capability to handle date-time axes, e.g., the axis labels can be based on an encoded date-time value, displayed in anything from seconds to years. At the heart of the date-time axis is the To use a date-time axis in ZedGraph, you need to change to myPane.XAxis.Type = AxisType.Date;
ZedGraph will then assume that the X array Assuming If you want to try this out, here's the code for an example graph, which has a data point for the first day of each month, for 30 months starting with 1-Jan-1995: ![]() // Build the Chart
private void CreateGraph( ZedGraphControl zg1 )
{
// Get a reference to the GraphPane
GraphPane myPane = zg1.GraphPane;
// Set the titles
myPane.Title.Text = "My Test Date Graph";
myPane.XAxis.Title.Text = "Date";
myPane.XAxis.Title.Text = "My Y Axis";
// Make up some random data points
double x, y;
PointPairList list = new PointPairList();
for ( int i=0; i<36; i++ )
{
x = (double) new XDate( 1995, 5, i+11 );
y = Math.Sin( (double) i * Math.PI / 15.0 );
list.Add( x, y );
}
// Generate a red curve with diamond
// symbols, and "My Curve" in the legend
CurveItem myCurve = myPane.AddCurve( "My Curve",
list, Color.Red, SymbolType.Diamond );
// Set the XAxis to date type
myPane.XAxis.Type = AxisType.Date;
// Tell ZedGraph to refigure the axes since the data
// have changed
zg1.AxisChange();
}
The above code generates the following graph: In this case, ZedGraph selected a major step size of six days, and a minor step size of one day. You can easily adjust the selected format, if desired. For example, if you want to use 1 month for the minor step size, just set Text axisZedGraph also handles a text axis. This is an axis in which the tic labels are arbitrary, user supplied text strings instead of value labels. Internally, a text axis is handled using ordinal values just like an ordinary axis. In this case, the first major label has a value of 1.0, the second major label has a value of 2.0, etc. It is permissible to use fractional values if you want to place points in-between the labels. To make a text axis, you set Bar chartsZedGraph includes bar charting capability for vertical and horizontal bar charts, stacked bar charts, percent stacked bar charts, overlay bar charts, error bar charts, high-low bar charts, open-high-low-close bar charts, and Japanese candlestick bar charts. A bar chart is created similar to a line graph, except that you use Bars can be made horizontal or vertical, by setting the "base" axis to the X or Y axis. Under the ZedGraph terminology, the "base" axis determines the bar position, and the "value" axis determines the height of the bar. Typically, bar charts would be created with ZedGraph actually has six distinct bar types, any of which can be horizontal or vertical:
Other "bar-like" types are also available:
The following is an example of a The orientation (horizontal or vertical) and the size of the Two properties are included in the ![]() // Build the Chart
private void CreateGraph( ZedGraphControl zg1 )
{
// get a reference to the GraphPane
GraphPane myPane = zg1.GraphPane;
// Set the Titles
myPane.Title.Text = "My Test Bar Graph";
myPane.XAxis.Title.Text = "Label";
myPane.YAxis.Title.Text = "My Y Axis";
// Make up some random data points
string[] labels = { "Panther", "Lion", "Cheetah",
"Cougar", "Tiger", "Leopard" };
double[] y = { 100, 115, 75, 22, 98, 40 };
double[] y2 = { 90, 100, 95, 35, 80, 35 };
double[] y3 = { 80, 110, 65, 15, 54, 67 };
double[] y4 = { 120, 125, 100, 40, 105, 75 };
// Generate a red bar with "Curve 1" in the legend
BarItem myBar = myPane.AddBar( "Curve 1", null, y,
Color.Red );
myBar.Bar.Fill = new Fill( Color.Red, Color.White,
Color.Red );
// Generate a blue bar with "Curve 2" in the legend
myBar = myPane.AddBar( "Curve 2", null, y2, Color.Blue );
myBar.Bar.Fill = new Fill( Color.Blue, Color.White,
Color.Blue );
// Generate a green bar with "Curve 3" in the legend
myBar = myPane.AddBar( "Curve 3", null, y3, Color.Green );
myBar.Bar.Fill = new Fill( Color.Green, Color.White,
Color.Green );
// Generate a black line with "Curve 4" in the legend
LineItem myCurve = myPane.AddCurve( "Curve 4",
null, y4, Color.Black, SymbolType.Circle );
myCurve.Line.Fill = new Fill( Color.White,
Color.LightSkyBlue, -45F );
// Fix up the curve attributes a little
myCurve.Symbol.Size = 8.0F;
myCurve.Symbol.Fill = new Fill( Color.White );
myCurve.Line.Width = 2.0F;
// Draw the X tics between the labels instead of
// at the labels
myPane.XAxis.MajorTic.IsBetweenLabels = true;
// Set the XAxis labels
myPane.XAxis.Scale.TextLabels = labels;
// Set the XAxis to Text type
myPane.XAxis.Type = AxisType.Text;
// Fill the Axis and Pane backgrounds
myPane.Chart.Fill = new Fill( Color.White,
Color.FromArgb( 255, 255, 166), 90F );
myPane.Fill = new Fill( Color.FromArgb( 250, 250, 255) );
// Tell ZedGraph to refigure the
// axes since the data have changed
zg1.AxisChange();
}
The above code generates the following graph: Bar typesZedGraph can draw
The following samples show horizontal and stacked bar types: Pie chartsPie charts are created in the normal fashion using the Although it is technically possible to combine pie charts with line graphs on the same The following is an example of a ZedGraph pie chart: The MasterPaneThe Pan/Zoom functionsThe The Fill classThe
Internally, the
The following graph is an example of The following shows an example of using an image to fill in the bars of a bar chart: Z-OrderThe graphic items in the display are contained in two lists;
Utility methodsZedGraph is being used as a class library in interactive parent applications that need information about the graph. The following are some utility methods that are worth mentioning (these are documented in the ZedGraph.chm doc file):
AcknowledgementsI would like to thank all those who have tested the code, reported issues, and contributed code to the ZedGraph project. I would especially like to acknowledge the contributions of the volunteer developers who made ZedGraph possible: Jerry R. Vos, Bob Kaye, Darren Martz, and Benjamin Mayrargue. Latest update
JChampion
|
from
http://www.codeproject.com/csharp/zedgraph.asp 内容好多~
转载于:https://www.cnblogs.com/lxinxuan/archive/2007/04/27/729771.html