首页 > 解决方案 > C# 修复图表大小

问题描述

我正在创建一个从串行端口绘制数据的应用程序。我的问题是,有时当值低于 X 轴时图表大小会增加,因此 X 轴上的某些值会消失。

我已经设置了最小和最大 Y 轴值,所以我想知道水平轴如何可能会轻轻向下移动一段时间然后消失 - 可能是由于空间不足?

它只出现在第一个和最后一个标签上,有时最后一个网格线也会消失。

这是生成图表值的一段代码:

    int minStress = -200, maxStress=200;
    double maxTime=20.0, minTime=0.0;
    private void timer1_Tick(object sender, EventArgs e)
    {

        Stress = serialPort1.ReadLine();
        label6.Text = Stress;
        StressChart.ChartAreas[0].AxisX.Minimum = minTime;
        StressChart.ChartAreas[0].AxisX.Maximum = maxTime;
        StressChart.ChartAreas[0].AxisX.ScaleView.Zoomable = true;
        StressChart.ChartAreas[0].AxisY.ScaleView.Zoomable = true;
        this.StressChart.Series[0].Points.AddXY((minTime + maxTime) / 2, Stress);
        minTime=minTime + TimerInt_2/1000;
        maxTime=maxTime + TimerInt_2/1000;
        serialPort1.DiscardInBuffer();

    }
    private void cmbTimerInt_SelectedIndexChanged(object sender, EventArgs e)
    {
        TimerInt = int.Parse(cmbTimerInt.Text);
        TimerInt_2=double.Parse(cmbTimerInt.Text);
        timer1.Interval = TimerInt;
    }
    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        try
        {
            minStress = int.Parse(textBox1.Text);
        }
        catch { }
        if (minStress < maxStress)
        {
            StressChart.ChartAreas[0].AxisY.Minimum = minStress;
        }
    }

    private void textBox2_TextChanged(object sender, EventArgs e)
    {
        try
        {
            maxStress = int.Parse(textBox2.Text);
        }
        catch { }
        if (maxStress > minStress)
        {
            StressChart.ChartAreas[0].AxisY.Maximum = maxStress;
        }
    }

这是设置图表属性的代码:

            chartArea1.AxisX.LabelStyle.Format = "0.0";
        chartArea1.Name = "ChartArea1";
        this.StressChart.ChartAreas.Add(chartArea1);
        legend1.Name = "Legend1";
        this.StressChart.Legends.Add(legend1);
        this.StressChart.Location = new System.Drawing.Point(225, 12);
        this.StressChart.Name = "StressChart";
        series1.ChartArea = "ChartArea1";
        series1.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Spline;
        series1.Legend = "Legend1";
        series1.Name = "Series1";
        this.StressChart.Series.Add(series1);
        this.StressChart.Size = new System.Drawing.Size(1175, 426);
        this.StressChart.TabIndex = 5;
        this.StressChart.Text = "chart1";
        chartArea1.AxisX.LabelAutoFitStyle = 0;
        chartArea1.AxisY.LabelAutoFitStyle = 0;
        chartArea1.AxisX.MajorTickMark.Size = 0;
        chartArea1.AxisX.IsMarginVisible = true;
        chartArea1.AxisY.IsMarginVisible = true;

图表的图像

标签: c#

解决方案


这种行为的原因是 X 轴标签的小数位数。解决方案是将这些值四舍五入到小数点后一位。

minTime = Math.Round(minTime,1) + Math.Round(TimerInt_2/1000,1);
maxTime = Math.Round(maxTime,1) + Math.Round(TimerInt_2/1000,1);

推荐阅读