How to add data table with legend keys to a MS Chart in C#?

纵饮孤独 提交于 2019-11-27 05:41:38

Yes you can do that:

Here are the steps I took:

First we disable the original Legend as it can't be manipulated the way we need to..:

chart1.Legends[0].Enabled = false;

Now we create a new one and a shortcut reference to it:

chart1.Legends.Add(new Legend("customLegend"));
Legend L = chart1.Legends[1];

Next we do some positioning:

L.DockedToChartArea = chart1.ChartAreas[0].Name;  // the ca it refers to 
L.Docking = Docking.Bottom;
L.IsDockedInsideChartArea = false;
L.Alignment = StringAlignment.Center; 

Now we want to fill in one line for headers and one line per series.

I use a common function for both and pass in a flag to indicate whether the headers (x-values) or the cell data (y-values) should be filled in. Here is how I call the function:

addValuesToLegend(L, chart1.Series[0], false);
foreach (Series s in chart1.Series) addValuesToLegend(L, s, true);

Note that for this to work we need a few preparations in our Series:

  • We need to set the Series.Colors explicitly or else we can't refer to them.
  • I have added a format string to the Tag of each series; but maybe you find a better solution that avoids hard-coding the format for the header..

So here is the function that does all the filling and some styling:

void addValuesToLegend(Legend L, Series S, bool addYValues)
{
    // create a new row for the legend
    LegendItem newItem = new LegendItem();
    // if the series has a markerstyle we show it:
    newItem.MarkerStyle = S.MarkerStyle ;
    newItem.MarkerColor = S.Color; 
    newItem.MarkerSize *= 2;   // bump up the size
    if (S.MarkerStyle == MarkerStyle.None)
    {
        // no markerstyle so we just show a colored rectangle
        // you could add code to show a line for other chart types..
        newItem.ImageStyle = LegendImageStyle.Rectangle;
        newItem.BorderColor = Color.Transparent;
        newItem.Color = S.Color;
    }
    else newItem.ImageStyle =  LegendImageStyle.Marker;

    // the rowheader shows the marker or the series color
    newItem.Cells.Add(LegendCellType.SeriesSymbol, "", ContentAlignment.MiddleCenter);
    // add series name
    newItem.Cells.Add(LegendCellType.Text, addYValues ? S.Name : "",
                      ContentAlignment.MiddleLeft);
    // combine the 1st two cells:
    newItem.Cells[1].CellSpan = 2;

    // we hide the first cell of the header row
    if (!addYValues)
    {
        newItem.ImageStyle = LegendImageStyle.Line;
        newItem.Color = Color.Transparent;
        newItem.Cells[0].Tag = "*";  // we mark the 1st cell for not painting it
    }
    // now we loop over the points:
    foreach (DataPoint dp in S.Points)
    {
        // we format the y-value
        string t = dp.YValues[0].ToString(S.Tag.ToString());
        // or maybe the x-value. it is a datatime so we need to convert it!
        // note the escaping to work around my european locale!
        if (!addYValues) t = DateTime.FromOADate(dp.XValue).ToString("M\\/d\\/yyyy");
        newItem.Cells.Add(LegendCellType.Text, t, ContentAlignment.MiddleCenter);
    }
    // we can create some white space around the data:
    foreach (var cell in newItem.Cells)  cell.Margins = new Margins(25, 20, 25, 20);
    // finally add the row of cells:
    L.CustomItems.Add(newItem);
}

To draw the borders around the cells of our legend table we need to code the PrePaint event:

private void chart1_PrePaint(object sender, ChartPaintEventArgs e)
{
    LegendCell cell = e.ChartElement as LegendCell;
    if (cell != null && cell.Tag == null) 
    {
        RectangleF r = e.ChartGraphics.GetAbsoluteRectangle(e.Position.ToRectangleF());
        e.ChartGraphics.Graphics.DrawRectangle(Pens.DimGray,Rectangle.Round(r));
        // Let's hide the left border when there is a cell span!
        if (cell.CellSpan != 1) 
                e.ChartGraphics.Graphics.DrawLine(Pens.White, 
                                r.Left, r.Top+1, r.Left, r.Bottom-1);
    }
}

You can add more styling although I'm not sure if you can match the example perfectly..

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!