Search code examples
c#winformsmschart

Custom chart elements


I want to make a chart in C# with custom elements. What I have:

enter image description here

What I want:

enter image description here

Elements marked by red circles need to be replaced by the image. My program code is very short, just some values for the chart. All settings for chart were set by the "Collection" in Chart section (as shown on first image).


Solution

  • This is a BoxPlot chart and it takes 6 y-values.

    You can add them or let the chart calculate them.

    Looks like you want to add several images to the various y-values..

    Here is an example of how to do that by owner-drawing the Chart. (No, not the whole chart, just a little extra custom-drawing ;-)

    It adds an image to each of the y-values; it should be easy to adapt to only those values you really want. And if you only want one you may even do away with the ImageList and pick the image from the resources; (although using an ImageList is a nice way, as long as you can live with the limitations of 256x256 maximum size and all images having the same size and color depth..)

    You seem to want one of these only:

    4 Average and mean

    5 Median

    private void chart_PostPaint(object sender, ChartPaintEventArgs e)
    {
        Series s1 = chart.Series[0];
        ChartArea ca = chart.ChartAreas[0];
        Axis ax = ca.AxisX;
        Axis ay = ca.AxisY;
        Graphics g = e.ChartGraphics.Graphics;
        int iw = imageList1.ImageSize.Width / 2;
        int ih = imageList1.ImageSize.Height / 2;
        foreach (DataPoint dp in s1.Points)
        {
            int x = (int) ax.ValueToPixelPosition(dp.XValue);
            for (int i = 0; i < 6; i++)
            {
                int y = (int) ay.ValueToPixelPosition(dp.YValues[i]);
                g.DrawImage(imageList1.Images[i], x - iw, y - ih);
            }
        }
    }
    

    enter image description here

    I suggest to use png files with transparency and an odd width so they look nice and centered. (I used randomly 16x16, which is not quite that nice ;-) - For this you need to set the ImageSize and the ColorDepth of the ImageList.

    To further style the chart you may use these special properties

    Custom attributes

    BoxPlotPercentile, BoxPlotSeries, BoxPlotShowAverage, BoxPlotShowMedian, BoxPlotShowUnusualValues, BoxPlotWhiskerPercentile, DrawSideBySide, MaxPixelPointWidth, MinPixelPointWidth, PixelPointDepth, PixelPointGapDepth, PixelPointWidth, PointWidth

    Note that you need to set them all as strings, maybe like this:

      s1.SetCustomProperty("someAttribute", "someValue");