MS Chart Control: Getting Started
2010-05-06 22:05 3895人阅读 评论(1) 收藏 举报
Scott Mitchell wrote a great series of articles where he describes how to use Microsoft Chart control from simple binding to more complex scenarious. I highly recommend to read his articles for everybody starting working on the control: http://www.4guysfromrolla.com/articles/072209-1.aspx
Alex.
Posted by alexgor | 4 Comments
Filed under: Chart, .NET Framework, Microsoft Chart Control
Tuesday, October 06, 2009 8:33 AM
Setting Microsoft Chart Series Colors
Microsoft Chart control provides different ways to set color of the series and data points:
Palettes
Selecting one of the predefined palettes is the easiest way to change chart series colors. There are 12 built-in palettes with about 10 unique colors each.
Chart types like column and line, will assign a unique color from the palette to each of the series. If chart runs out of the palette colors then it will start reusing them again.
// Set chart series palette
Chart.Palette = ChartColorPalette.Pastel;
Chart type like Pie, assigns unique colors to each individual data point. You can still use Chart.Palette property or you can define different palettes for different series using Series.Palette property. Note that setting Series.Palette property will force all chart types including Column to use unique colors for each data point.
Important! To determine the color assigned to the series or data point from the palette you can call chart1.ApplyPaletteColors() method and then check Series or DataPoint.Color property.
Custom Palettes
If none of the predefined palettes fits your needs, you can always create custom palette with as many colors as you need:
// Set chart custom palette
Chart.Palette = ChartColorPalette.None;
Chart.PaletteCustomColors = new Color[] { Color.Red, Color.Blue, Color.Yellow};
Empty points
Not all series data points are equal… When you data bind your chart to the DBNull values the data points will be automatically marked as ‘empty’. You can also mark data points as empty by setting DataPoint.IsEmpty property. Each empty data point uses the visual attributes defined in Series.EmptyPointStyle property.
// Hide all series empty data point by making them transparent
Chart.Series[0].EmptyPointStyle.Color = Color.Transparent;
Color Property
If all of the above methods does not work for you, then you can always set Color property for the series or individual data point.
// Set color for the whole series
Chart.Series[0].Color = Color.Green;
// Set color of a single data point
Chart.Series[0].Points[5].Color = Color.Red;
You can always switch back to using the palette colors by setting both Series and DataPoint Color properties to Color.Empty.
Alex.
Posted by alexgor | 1 Comments
Filed under: Chart, .NET Framework, Microsoft Chart Control
MS Chart consists of different elements (like titles, legends, chart areas, …) which all share the same space in the chart. It is easy to make a ‘perfect’ layout of these elements when you know exactly how many you will have and what size they going to be. It can be challenging when the content of these elements is dynamic and their size may change significantly. Today we will discuss how we can improve different aspects of the Chart elements layout.
Examples
First of all, let’s start by looking at several different charts before (left) and after (right) we applied our layout improvement rules.
Example 1: Legend position was changed from Bottom to Right and its’ width was truncated.
Sample 2: Title font was reduced and legend position switched from Bottom to Right.
Sample 3: Vertical axis labels were limited to 30% of the chart width.
Sample 4: Bottom axis long labels are truncated and vertical axis labels are shown in thousands.
Sample 5: Labels are shown only for the largest 7 slices in the Pie.
Legend
The most common issue with the Legend, is that it can take significant amount of chart space and can make the actual chart data difficult to read. Here are things that can improve legend layout:
- Legend is docked depending on the proportions of the chart so that it takes advantage of the available space. For example, if we have a wide chart, it is better to dock legend on the Right than on the Bottom of the chart.
- Limit space available to the legend to 30% of the total chart space. Legend will be trimmed if its’ content exceeds 30% of the chart size.
- Hide legend when chart becomes too small.
Title
If chart title content depends on the dynamic data, its’ size can grow unpredictably and interfere with the data we are trying to shown in the chart. This is very similar with the Legend issues described above.
- Limit space available to the title to 20% of the total chart space. If title exceeds 20%, we will try to reduce its’ font size and then truncate the content.
- Hide title when chart becomes too small.
Axis Labels
A single very long label can make chart very hard to read.
- Limit maximum size available to the axis labels to 30% of the chart size. If labels can not fit their content will be automatically truncated.
- Use multipliers for showing values in thousands, millions, billions,… Instead of showing a very long axis label like this ‘50,000,000.00’, you can display ‘50’ and add ‘(in millions)’ to the axis title.
Pie Labels
Pie chart type is not the best visualization if you need to display many (>10) data points. It is hard to read and if you enable data point labels, there is a high chance that they will start overlapping. If you have to us the Pie chart it makes sense to show labels only for the largest slices in the pie.
- Only display labels for the largest 7 slices in the Pie or Doughnut chart.
How to use?
All these rules are implemented and can be automatically applied using ChartLayoutUtilities add-on. Attached project contains ChartLayoutUtilities class and a sample Web Form. Just create an instance of this call passing reference to the chart control!
Alex.
Posted by alexgor | 1 Comments
Filed under: Chart, Microsoft Chart Control
Attachment(s): ChartsWithLongLabels.zip
Friday, March 27, 2009 6:51 PM
Displaying Categorical Axis Labels.
In this post I will discuss labeling of the categorical axes in SQL Reporting Services (SSRS) and .NET Chart controls. Same engine is used between these two products and they have exactly the same behavior. You can find detailed steps and sample code at the end of the post.
Before we start, lets have a look how automatic chart axis labels work... When you data bind your chart, axis automatically calculates data scale and sets axis Minimum and Maximum values. Based on the axis scale, chart determines axis labels text, interval (how often labels are shown), font size and label rotation, so that labels do not overlap each other. Below you can see a simple chart with categorical values (countries) shown on the bottom axis:
As you can see, there is not enough space to show all the labels and chart only displays every other country. For categorical axis it is important to show as many categories as possible and here are few different tricks which will help you achieving that.
Solution 1: Force chart axis to display every category.
Chart axis Interval property allows you to provide your own custom interval for axis labels, grid lines and tick marks. Our first solution is to set this property to 1, which will force the chart to display every single category. As you can see on the chart below, every country will become visible and chart will automatically rotate labels to better fit them. If you are using Column chart type you can also switch to Bar chart type to avoid labels rotation.
This is a very simple approach but you should also be aware of the possible down sides. In case you have too many categories, labels auto-fit algorithm may not be able to completely avoid labels overlapping and they will be very hard to read. I simulated this by reducing our original chart width in half and as you can see it is very hard to read the labels. If we double number of data points (countries) it will be even harder to read this chart.
Solution 2: Enable Variable Count interval and set preferred labels appearance
Second solution keeps the axis Interval in automatic mode, so that in extreme cases we can still reduce number of labels on the axis. First step is to disable labels auto fitting and specify the preferred font size and rotation. In our case we are trying to fit as much labels as possible, so we will set axis labels rotation angle to 90 degrees. And the last step is to enable Variable Interval calculation mode on the axis. By default, chart displays about 5 labels on the axis no matter how long it is, Variable Interval mode will allow you display as many labels as we can fit into the axis. After all this changes you should see something very similar to the Solution 1 chart:
Now let's try to reduce the size of the chart and see what will be different... As you can see in the image below, when chart cannot fit more vertically oriented labels it starts skipping them to avoid making chart completely unreadable.
Conclusion
When categories are displayed on the axis, there is no grantee that all of them will be shown. You can set axis interval to 1 if it is extremely important to see every category but keep in mind that labels may overlap if there are too many categories. Use Variable Interval and labels rotation if you want to fit as many labels as possible and still have labels skipping in extreme cases.
SSRS Steps
Steps to apply Solution 1:
- Right click on the bottom axis and choose Axis Properties from the context menu
- Set Interval field to 1 in the Axis Options property page
- Press Ok to close property dialog
Steps to apply Solution 2:
- Make sure Properties View is enabled
- Click on the axis to select it and display it's properties in the Properties View
- Set VariableAutoInterval property to True
- Set LabelsAngle property to 90
- Click Yes on the pop-up dialog to labels disable auto fitting
.NET Chart Sample Code
// Solution 1: Setting axis Interval |
this.Chart1.ChartAreas[0].AxisX.Interval = 1; |
|
// Solution 2: Enable variable interval |
this.Chart1.ChartAreas[0].AxisX.Interval = double.NaN; |
this.Chart1.ChartAreas[0].AxisX.IntervalAutoMode = IntervalAutoMode.VariableCount; |
this.Chart1.ChartAreas[0].AxisX.LabelStyle.Angle = 90; |
Alex.
Posted by alexgor | 1 Comments
Filed under: Chart, Microsoft Chart Control, Reporting Services, SSRS
Friday, March 27, 2009 5:35 AM
Aligning Multiple Series with Categorical Values
Binding Categorical Data Overview
Binding chart to the data source with categorical values is pretty simple and usually requires just one line of code:
Chart1.Series["Series1"].Points.DataBind(mySource, "ProductName", "Sales"); |
It is important to understand that after DataBind method creates series DataPoint objects, their XValue property will always be set to zero and category is saved in the AxisLabel property. Position of each data point along the category axis is determined using the index of the object in Series.Points collection. Below is an example of what your chart may look like:
Alignment of Multiple Series
When you bind multiple series with categorical values you may run into some un-expected results based on how you prepare your data source. For example, let's imagine that our two chart series are bound to this data:
Series 1 | Series 2 |
Product A = 320 | Product B = 420 |
Product B = 580 | Product E = 830 |
Product C = 980 |
|
Product E = 100 |
|
Product F = 220 |
|
As you can notice, we have less categories for the second series and their order does not match categories from the first series. If we try binding chart to this data we will end up with the chart shown below. Chart uses index of the data point to position them along the axis and we end up with orange series points in the wrong position. I added data point labels so that it would easier to see the issue.
In order to resolve this we can modify our data source to contain same number of categories in the same order like this:
Series 1 | Series 2 |
Product A = 320 | Product A = Null |
Product B = 580 | Product B = 420 |
Product C = 980 | Product C = Null |
Product E = 100 | Product E = 830 |
Product F = 220 | Product F = Null |
Simpler approach is just to make a single call to Chart.AlignDataPointsByAxisLabel method which will automatically align the two series by inserting empty points and the end result will look like this:
Hope this helps!
Alex.
Posted by alexgor | 1 Comments
Filed under: Chart, Microsoft, Microsoft Chart Control
Friday, March 06, 2009 5:47 PM
Charting With ASP.NET and LINQ
Check out the new MSDN article about how to use ASP.NET Chart control with LINQ by K. Scott Allen: http://msdn.microsoft.com/en-us/magazine/dd453008.aspx
Alex.
Posted by alexgor | 0 Comments
Filed under: Chart, ASP.NET, MSDN, LINQ
Friday, February 27, 2009 6:45 PM
Deploying Microsoft Chart Controls
MSChart.exe setup should be used to deploy Microsoft Chart controls but what exactly need to be done to create a deployment package in Visual Studio? Visual Studio provides an easy way to add the prerequisites using bootstrappers, and thanks to Phil Preen, now we have a detailed instructions on how to create and use .NET Chart Control bootstrapper.
You can find his article here: http://www.philpreen.co.uk/MSChart/
Alex.
Posted by alexgor | 1 Comments
Filed under: Chart, Microsoft Chart Control, Bootstrapper, Deployment
Saturday, February 21, 2009 2:42 AM
Data Binding Microsoft Chart Control
Overview
When you add a new visualization in your application, the very first thing you do, is bind it to the data. Microsoft Chart control allows many different ways of populating data in the chart and it is important to understand the differences between them and being able to choose the best approach. I put together all the possible data binding options and the scenarios when they should be used.
Data Sources
Before jumping into the binding methods I want to quickly list all the supportable data sources which can be used in chart binding methods. Keep in mind that not all methods accept all source types.
- SqlCommand
- OleDbCommand
- SqlDataAdapter
- OleDbDataAdapter
- DataView
- DataSet
- DataReader
- List
- Array
- IList
- IListSource
- IEnumerable
Data Point X and Y values
When you bind chart you create series and series data points. Each data point in the series should have it's Y value set and in addition to the Y value you can also bind or set other data point properties:
- X Value - Defines location of the data point along X axis. If not specified, data point index in the series will be used.
- Additional Y Values - Chart types like Bubble or Stock require multiple Y values. You can also bind additional Y values in the regular chart types, if you want to use those values for labels or tooltips.
- Category - When you displaying categories on the X axis, they are stored in the AxisLabel property of the data point. All data binding methods will automatically detect the type of the data and you should not worry about it.
- Other Properties - Some of the binding methods allow you to set additional properties like data point labels, tooltips and others.
Binding Options Overview
This table lists data binding techniques, starting from the most basic methods proceeding to more advanced.
Chart.DataBindTable |
|
|
Chart.DataSource and Chart.DataBind |
|
|
Points.DataBind(X)Y |
|
|
Points.DataBind |
|
|
Chart.DataBindCrossTab |
|
|
Binding Options Details
Chart.DataBindTable method
The Chart.DataBindTable method is the simplest way to bind chart to a table with several columns. New series will be automatically created for each of the columns and you can optionally use one column for the X value for all series.
Example
Imagine you have a data source containing these columns: Prod A, Prod B, Prod C, Prod D, Prod E, Other and SalesName, you can easily create chart below with a single line of code:
Chart1.DataBindTable(myReader, "SalesName"); |
Chart.DataSource property
Chart DataSource property is the only way to bind chart at design-time. In addition to specifying the DataSource property you also need to create series and set their YValueMembers and optionally XValueMember properties. Multiple Y values can be bound if you specify comma separated list of members in the YValueMembers property.
Chart will automatically bind itself to specified data source and members just before rendering. You can force chart to bind at any moment by calling Chart.DataBind() method.
// Set chart data source |
chart1.DataSource = myCommand; |
|
// Set series members names for the X and Y values |
chart1.Series["Series 1"].XValueMember = "Name"; |
chart1.Series["Series 1"].YValueMembers = "Sales"; |
|
// Data bind to the selected data source |
chart1.DataBind(); |
DataBindCrossTab
The Chart.DataBindCrossTab is different compared to all other binding methods, in that it allows for the grouping of unique values in a column. Each unique value in the specified grouped column results in the creation of a data series. In addition, extended data point properties other than X and Y values can be bound.
These other properties are bound using the otherFields parameter using this syntax:
PointProperty=Field[{Format}] [,PointProperty= Field[{Format}]].
A list of these properties are as follows: AxisLabel, Tooltip, Label, LegendText, LegendTooltip and CustomPropertyName (the name of a custom property). For more information on possible formats see the Formatting Types topic in the MSDN library.
Example
In the sample below we have a table that has the sales and commissions of sales people for three years. We group by the "Name" column, thereby creating one data series per sales person. The X values are bound to the "Year" column, the Y values are bound to the "Sales" column, the Label property of the resulting data points (one per record) is bound to the "Commissions" column, and the LegendText property is bound to the "Name" column.
// Group by "Name" column, bind X values to "Year", Y values to "Sales", |
// and Label property to "Commissions. |
chart1.DataBindCrossTab(myReader, "Name", "Year", "Sales", "Label=Commissions"); |
Points.DataBind
This method allows for data point properties other than X and Y values to be bound to data columns. For example, you want to set data point label to a value in one of the data source columns. These other properties are bound using the otherFields parameter using this syntax:
PointProperty=FieldName[{Format}][,PointProperty= FieldName[{Format}]]
A list of these properties includes: AxisLabel, Tooltip, Label, LegendText, LegendTooltip and CustomPropertyName (the name of a custom property).
This method does not allow you to specify separate data sources for the X and Y values of a series (for this functionality use the DataBind(X)Y methods described in the section above).
Example
Code below demonstrates how to bind X and Y values of the series to columns "Name" and "Sales" respectively. The Label and Tooltip properties of the resulting data points are also bound to the "Commissions" and "Year" column.
Chart1.Series["Series1"].Points.DataBind( |
myReader, "Name", "Sales", "Tooltip=Year, Label=Commissions{C2}"); |
|
Points.DataBind[X]Y
The DataBindXY method allows for the binding of X and Y values of a series, while DataBindY binds Y values only. When binding X and Y values using DataBindXY the same or different data sources may be used.
Some data sources support multiple values (e.g. data sources that have columns of data). For example, OleDbDataReader may have access to more than one column of data. If the column to be used is not specified, then the first available column will be used. To use a column other than the first one just specify the column name in the method call.
Note that when specifying the column names to be bound to the Y values a comma can be embedded as part of a column name by specifying a double comma.
Example
Code below demonstrates how to bind series points to the array of doubles.
// Initialize an array of doubles. |
double [] array = { 2.8, 4.4, 6.5, 8.3, 3.6, 5.6, 7.3, 9.2, 1.0}; |
|
// Bind the double array to the Y axis points of the data series. |
Chart1.Series["Series1"].Points.DataBindY(array); |
'Manual' series population
In case you need to perform some custom actions while binding and none of the above methods works, you can always 'manually' bind chart by iterating through the data source and add data points to the series as needed. This approach is also very useful when series data is calculated using some formula.
Example
// Resolve the address to the Access database |
string fileNameString = this.MapPath("."); |
fileNameString += "..//..//..//data//chartdata.mdb"; |
|
// Initialize a connection string |
string myConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileNameString; |
|
// Define the database query |
string mySelectQuery="SELECT * FROM SALESCOUNTS;"; |
|
// Create a database connection object using the connection string |
OleDbConnection myConnection = new OleDbConnection(myConnectionString); |
|
// Create a database command on the connection using query |
OleDbCommand myCommand = new OleDbCommand(mySelectQuery, myConnection); |
|
// Open the connection |
myCommand.Connection.Open(); |
|
// Initializes a new instance of the OleDbDataAdapter class |
OleDbDataAdapter myDataAdapter = new OleDbDataAdapter(); |
myDataAdapter.SelectCommand = myCommand; |
|
// Initializes a new instance of the DataSet class |
DataSet myDataSet = new DataSet(); |
|
// Adds rows in the DataSet |
myDataAdapter.Fill(myDataSet, "Query"); |
|
foreach(DataRow row in myDataSet.Tables["Query"].Rows) |
{ |
// For each Row add a new series |
string seriesName = row["SalesRep"].ToString(); |
Chart1.Series.Add(seriesName); |
Chart1.Series[seriesName].ChartType = SeriesChartType.Line; |
Chart1.Series[seriesName].BorderWidth = 2; |
|
for(int colIndex = 1; colIndex < myDataSet.Tables["Query"].Columns.Count; colIndex++) |
{ |
// For each column (column 1 and onward) add the value as a point |
string columnName = myDataSet.Tables["Query"].Columns[colIndex].ColumnName; |
int YVal = (int) row[columnName]; |
|
Chart1.Series[seriesName].Points.AddXY(columnName, YVal); |
} |
} |
|
DataGrid.DataSource = myDataSet; |
DataGrid.DataBind(); |
|
// Closes the connection to the data source. This is the preferred |
// method of closing any open connection. |
myCommand.Connection.Close(); |
|
Other useful things to know
Here are couple things that you should know about when binding chart:
- Empty Points - Understand what empty points are and how you can use them. Right now the best source of the information is Chart Sample Environment but I will blog about it later.
- AlignDataPointsByAxisLabel - If you are using a stacked chart type with categorical X axis this helper method can be very useful. Find more information in the documentation and Chart Sample Environment.
Posted by alexgor | 7 Comments
Filed under: Chart, Windows Forms, ASP.NET, Microsoft Chart Control, Data Binding
Friday, February 20, 2009 6:49 AM
Have a question about the ASP.NET chart control? Want to meet and discuss the future visualization roadmap? I will be at the ASP.NET Connections March 22-25. See you there!
http://www.devconnections.com/
Alex.
Posted by alexgor | 1 Comments
Filed under: Chart, ASP.NET, DevConnections
Monday, January 12, 2009 7:56 PM
Delian Tchoparinov just posted on his blog about chart image rendering using Chart HTTP Handlers. This is very useful reading for everybody using the ASP.NET version of the Microsoft Chart control. You can find this post here.
Alex.
Posted by alexgor | 2 Comments
Filed under: Chart, ASP.NET, Microsoft Chart Control, HTTP Handler
Thursday, December 04, 2008 3:49 PM
You can easily create charting SharePoint Web Part using new Microsoft Chart Control. Wictor Wilen created a "ChartPart for SharePoint" project on Codeplex, which is a ready to use WebPart with source code. If you want to create your own WebPart also check out this tutorial created by Marc Charmois!
Alex.
Posted by alexgor | 0 Comments
Filed under: Chart, Microsoft Chart Control, MOSS, SharePoint, WebPart
Wednesday, December 03, 2008 3:12 AM
Microsoft Chart Control How-to: Improve Chart Performance
There are several main areas that affect performance of the chart:
- Data binding.
- Rendering of the chart visual elements.
- Streaming chart image from the server to the client. (ASP.NET only)
The following chart scenarios may have a major impact on performance and we going to discuss their affect in details below:
- Large data sets
- Chart type used
- Data point tooltips
- Hyperlinks using the Url property
- Image size and type
- Border skins
- View state
Binding to Large Data Sets
When a chart is bound to a data set with over a 1000 data points, binding performance can take significant amount of time.
To optimize chart performance, we recommend the following:
- Optimize your query
- Avoid multiple passes through the data
Optimizing the query
Make sure you optimize the way you retrieve the data and that you only getting the data you need to display in the chart. You may consider grouping data to decrease total number of points. For example, if you display stock data for 5 years, instead of returning daily stock price you can aggregate it into the weekly price.
Avoid multiple passes through large data set
If you binding multiple series, make sure you are iterating the data source only once. Do not use DataBindXXX methods for each of the series, because each of this calls will iterate through the data source.
The best approach is to use DataBindCrossTab method of the chart or 'manually' iterate once through the data source and add points in the chart using AddXY method of DataPointCollection object.
Spline vs. Line vs. FastLine Charts
Selection of the chart type if you have a significant amount of data points in the series will have a significant impact on the chart performance.
For example, Spline charts are known to degrade performance, since they are actually calculated areas. This means that they require a great deal of calculation in order to be drawn, especially in 3D mode. The necessary calculations, and processing are being done by the GDI+ engine.
For optimal performance, we recommend avoiding spline-type charts if possible. Try using another chart type, such as a line chart instead.
In cases when you need to draw more than 100,000 data points you may also consider using FastLine and FastPoint chart types. They do not support all the features of the regular Line and Point chart but will SIGNIFICANTLY improve chart performance.
Tooltips
If there are numerous chart series data points, displaying them using the Tooltip property will seriously affect performance, since each tooltip results in the creation of a map area element. In addition to this, each tooltip must be calculated by the chart every time it is redrawn. Thus, if a chart has 1000 data points, all with an associated tooltip, then the page that displays the chart image will have 1000 MapArea elements for the tooltips. In ASP.NET application MapAreas are rendered as part of the page and may take significant time to download to the client.
If performance is critical and chart contain significant amount of data points consider avoiding using of tooltips. In Windows Forms application it may be more efficient to create on-demand tooltip using the timer and HitTest function of the chart.
Hyperlinks and Map Area attributes (ASP.NET only)
Care must also be taken when setting the Url and MapAreaAttributes properties. This situation is similar to using tooltips, since each chart element that has its Url property set, which results in a MapArea element that is recalculated each time the chart is redrawn.
If you must use one of the Tooltip, Url or MapAreaAttributes properties, using the second property has little affect.
Image Size and Type (ASP.NET only)
The larger the image size of the chart, the longer it will take to be streamed back to the requesting client. Also, the type of image being generated will affect its size. For example, a bitmap chart will be much larger than the exact same PNG chart. PNG is the recommended image type.
View State (ASP.NET)
Persisting the view state of the chart many data points may significantly increase the size of the response and amount of time required for the download.
Chart control provides additional functionality to optimize its view state. Please refer to the documentation and Chart Sample Framework.
Border Skins
Decorative borders, which can be set using the Chart.BorderSkin property, will also have a major impact on the chart's performance, since they require a considerable amount of time to render. You can gain some chart performance by removing them.
Hope this information is helpful and will allow you to squeeze more out of the Microsoft Chart Control!
Alex.
Posted by alexgor | 3 Comments
Filed under: Chart, Microsoft Chart Control, Performance
Sunday, November 30, 2008 2:08 AM
Microsoft Chart Control How-to: Using in a SharePoint web site
Thanks to Marc Charmois we have a very nice example of using the chart control in the SharePoint web site. Here is a link to his post…
I will continue collecting links to all the good posts regarding the chart control in my blog.
Alex.
Posted by alexgor | 1 Comments
Filed under: Microsoft Chart Control, MOSS, SharePoint
Wednesday, November 26, 2008 9:50 PM
Combining ASP.NET MVC and ASP.NET Charting Controls
Melvin Harbour recently posted in his blog about using ASP.NET Chart control with ASP.NET MVC.
Alex
Posted by alexgor | 1 Comments
Filed under: ASP.NET, Microsoft Chart Control, ASP.NET MVC
Tuesday, November 11, 2008 6:57 PM
Microsoft Chart Control How-to: Add Rich Content Using Keywords
Adding Labels or Tooltips is a simple task in the chart, but what if we want to show more data than just a simple data point value? Keywords allows specifying rich content for many text based properties, so that you can build a tooltip as shown in this Bubble chart image.
A Keyword is a specially formatted character sequence which can be used in many chart string properties to provide rich content. During the rendering of the chart, each Keyword is replaced with a value from the chart series or data point. For example, Keywords may be used to display several series values in the chart data point labels or tooltips. The sample below will display series data point Y value using the currency format string in the tooltip.
chart.Series[0].Tooltip = “Data Point Y Value: #VALY{C0}” |
As you may notice, to specify a tooltip on all chart data points we only need to set a single property of the series. You can use multiple keywords in one string and also specify optional formatting string.
Use cases
1) I want series data points to display a label with category name and price. Label example: "Bike -> $2.00"
series.Label = "#AXISLABEL -> #VALY{C}"; |
2) I'm using a Bubble chart with 2 Y values presenting model price and popularity index and I want to show this to values in my data points tooltip. Here is tooltip example:
"Model: XR300
Popularity Index: 4.5"
series.ToolTip = "Model: /t#AXISLABEL/nPopularity Index: /t#VALY"; |
3) I want to enable a postback and get an index of the data point the customer clicked on, so I can perform a drill-down action.
series.PostBack = "#INDEX"; |
4) I want to add additional columns in the legend to show average, minimum and total of my series as shown in the chart below:
// Add header separator of type line |
Chart1.Legends["Default"].HeaderSeparator = LegendSeparatorStyle.Line; |
Chart1.Legends["Default"].HeaderSeparatorColor = Color.Gray; |
|
// Add Color column |
LegendCellColumn firstColumn = new LegendCellColumn(); |
firstColumn.ColumnType = LegendCellColumnType.SeriesSymbol; |
firstColumn.HeaderText = "Color"; |
firstColumn.HeaderBackColor = Color.WhiteSmoke; |
Chart1.Legends["Default"].CellColumns.Add(firstColumn); |
|
// Add Legend Text column |
LegendCellColumn secondColumn = new LegendCellColumn(); |
secondColumn.ColumnType = LegendCellColumnType.Text; |
secondColumn.HeaderText = "Name"; |
secondColumn.Text = "#LEGENDTEXT"; |
secondColumn.HeaderBackColor = Color.WhiteSmoke; |
Chart1.Legends["Default"].CellColumns.Add(secondColumn); |
|
// Add AVG cell column |
LegendCellColumn avgColumn = new LegendCellColumn(); |
avgColumn.Text = "#AVG{N2}"; |
avgColumn.HeaderText = "Avg"; |
avgColumn.Name = "AvgColumn"; |
avgColumn.HeaderBackColor = Color.WhiteSmoke; |
Chart1.Legends["Default"].CellColumns.Add(avgColumn); |
|
// Add Total cell column |
LegendCellColumn totalColumn = new LegendCellColumn(); |
totalColumn.Text = "#TOTAL{N1}"; |
totalColumn.HeaderText = "Total"; |
totalColumn.Name = "TotalColumn"; |
totalColumn.HeaderBackColor = Color.WhiteSmoke; |
Chart1.Legends["Default"].CellColumns.Add(totalColumn); |
|
// Set Min cell column attributes |
LegendCellColumn minColumn = new LegendCellColumn(); |
minColumn.Text = "#MIN{N1}"; |
minColumn.HeaderText = "Min"; |
minColumn.Name = "MinColumn"; |
minColumn.HeaderBackColor = Color.WhiteSmoke; |
Chart1.Legends["Default"].CellColumns.Add(minColumn); |
|
Supported Keyword List
Here is the list of supported keywords. Chart control support multiple Y values and all related keywords use the first one by default but also can be used with additional Y values. For example:
“High=#VALY/nLow=#VALY2/nOpen=#VALY3/nClose=#VALY4”
An optional format string can be added at the end of each keyword. You can find more about possible format strings from here: http://msdn.microsoft.com/en-us/library/427bttx3.aspx Below is an example of using standard currency format and custom format string:
“Price= #VALY2{C0}/nAverage Price = #AVGY2{C0}/nVolume = #VALY3{#,,.;(#,,.);0}”
Keyword | Replaced By | Supports Multiple Y Values | Supports Formatting String |
#VALX | X value of the data point. | No | Yes |
#VALY | Y value of the data point | Yes | Yes |
#SERIESNAME | Series name | No | No |
#LABEL | Data point label | No | No |
#AXISLABEL | Data point axis label | No | No |
#INDEX | Data point index in the series | No | Yes |
#PERCENT | Percent of the data point Y value | Yes | Yes |
#LEGENDTEXT | Series or data point legend text | No | No |
#CUSTOMPROPERTY(XXX) | Series or data point XXX custom property value, where XXX is the name of the custom property. | No | No |
#TOTAL | Total of all Y values in the series | Yes | Yes |
#AVG | Average of all Y values in the series | Yes | Yes |
#MIN | Minimum of all Y values in the series | Yes | Yes |
#MAX | Maximum of all Y values in the series | Yes | Yes |
#FIRST | Y value of the first point in the series | Yes | Yes |
#LAST | Y value of the last point in the series | Yes | Yes |
Objects and Properties where keywords can be used
Series and DataPoint
- Label
- AxisLabel
- ToolTip
- Url
- MapAreaAttributes
- PostBackValue
- LegendToolTip
- LegendMapAreaAttributes
- LegendPostBackValue
- LegendUrl
- LegendText
- LabelToolTip
Annotation (only if anchored to the data point using SetAnchor method)
- ToolTip
- Url
- MapAreaAttributes
- PostBackValue
- Text (TextAnnotation)
LegendCellColumn (only for legend items automatically created for series or data points):
- Text
- Tooltip
- Url
- MapAreaAttributes
- PostBackValue