Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a chart in C# WinForms .NET 6

So I'm trying to create a chart in my .NET 6 WinForm application, and I can't find the charts option in my toolbox. Does anyone know why it is doing it? Did they remove charts in .NET 6? And if so, how can I create a chart? Thanks

like image 697
Someone with many names Avatar asked Mar 18 '26 05:03

Someone with many names


1 Answers

So, I found a work-around. It's not the most elegant, nor particularly performant, but since I just wanted a quick visualisation tool for internal testing, this did the trick nicely. Here's what I ended up with (basic scatter plot, but the principle can be adapted for line charts and box charts etc):

enter image description here

Process

  1. Add a picture box to your form
  2. populate it with an empty bitmap to the scale that you want to display
  3. for each data point you want to plot, draw a circle on the bitmap at those coordinates using Graphics.DrawEllipse

Example Code

    private void PlotCoordinates(List<Coordinates> coordinateList, Pen pen)
    {
        List<Rectangle> boundingBoxes = GenerateBoundingBoxes(coordinateList);

        using (Graphics g = Graphics.FromImage(image))
        {
            foreach (Rectangle boundingBox in boundingBoxes)
            {
                g.DrawEllipse(pen, boundingBox);
            }
        }
    }

    private List<Rectangle> GenerateBoundingBoxes(List<Coordinates> coordinateList)
    {
        var boundingBoxes = new List<Rectangle>(coordinateList.Count);

        //dataPointDiameterPixels is the diameter you want your ellipse to be on the plot
        //it needs to be an odd to be accurate
        int dataPointCetralisingOffset = dataPointDiameterPixels / 2;
        int rectLength = dataPointDiameterPixels;

        foreach (Coordinates coordinates in coordinateList)
        {
            int topLeftX = Maths.Max(coordinates.X - dataPointCetralisingOffset, 0);
            int topLeftY = Maths.Max(coordinates.Y - dataPointCetralisingOffset, 0);

            var box = new Rectangle(topLeftX, topLeftY, rectLength, rectLength);
            boundingBoxes.Add(box);
        }

        return boundingBoxes;
    }
like image 89
RCru Avatar answered Mar 19 '26 19:03

RCru



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!