Lei Yang
Lei Yang

Reputation: 4335

Winform Chart control - to keep displaying same bar width for different data

I'm familiar with C# and Winform, but new to Chart control. I'm using VS2013 built in System.Windows.Forms.DataVisualization.Charting.Chart to display bar for two points. Here's simply the code:

    private void Form1_Load(object sender, EventArgs e)
    {
        Chart c = new Chart();
        c.Dock = DockStyle.Fill;

        ChartArea a = new ChartArea();
        a.AxisX.Minimum = 0;
        a.AxisX.Maximum = 4;
        a.AxisY.Minimum = 0;
        a.AxisY.Maximum = 2;

        c.ChartAreas.Add(a);

        Series s = new Series();
        //*******************
        s.Points.AddXY(1, 1);
        //s.Points.AddXY(2, 2);
        s.Points.AddXY(3, 2);
        //*******************
        c.Series.Add(s);

        this.Controls.Add(c);
    }

enter image description here Please note the commented part, the points (2,2) and (3,2) are only different data, and have nothing to do with display style(I guess?). So this behavior seems very strange and so far I haven't found any solution to keep displaying (3,2) like (2,2).

Upvotes: 0

Views: 1235

Answers (1)

Techie
Techie

Reputation: 1491

You need to add the below codes in order to achieve the desired output:

1] Fix the interval for the Axis so the axis label and Grid lines do not change.

a.AxisX.Interval = 1;

2] Fix the bar width for the series. You can use PixelPointWidth to specify the width in Pixels or PointWidth in Points.

Example using PixelPointWidth:

s["PixelPointWidth"] = "20";

Also, since you are using c.Dock = DockStyle.Fill; to fill the chart into whole form, fixed width will not be good if you scale the form. You can use MinPixelPointWidth and MaxPixelPointWidth to give the range to the width.

s["MinPixelPointWidth"] = "20";
s["MaxPixelPointWidth"] = "80";

Check this link for details on different chart elements. Technical Reference for detailed documentation on Chart controls. This may be long but important to understand the details.

Upvotes: 2

Related Questions