MSChart - Auto Zoom Y Axis on X Axis Zoom

2019-01-26 21:49发布

问题:

I'm using MSChart and I want to enable zoom on the X Axis and once this is zoomed I want the Y Axis to auto zoom into a range appropriate for the data viewable.

Any assistance with the problem would be greatly appreciated!

Thanks

回答1:

The kind of zooming that you want to do cannot be automatically accomplished by MSChart. Once you have retrieved the 'Zoom-In' X-value range from the user, you need to write a little more code to reset the Y-axis scaling appropriately.

This works most easily if you are using a Line style of data series and your source data for that series is stored as a SortedList.

Dim firstXindex as Int32 = myDataSeries.IndexOfKey(firstXzoomValue)
Dim lastXindex as Int32 = myDataSeries.IndexOfKey(lastXzoomValue)    

Dim minY as Double = 1.7E+308
Dim maxY as Double = -1.7E+308  


For i = firstXindex To lastXindex
    If myDataSeries.GetByIndex(i) > maxY Then
        maxY = myDataSeries.GetByIndex(i)
    End If
    If myDataSeries.GetByIndex(i) < minY Then
        minY = myDataSeries.GetByIndex(i)
    End If
Next

Once you have used something like the code above to get your minY and maxY, you can then use those values to reset the min and max Y-axis values on the ChartArea:

With myChartArea
  .AxisY.Maximum = maxY
  .AxisY.Minimum = minY
End With


回答2:

I was searching for a solution for a long time. I found this useful. Subscribe to AxisValueChanged event and use ScaleView to modify the view.

private void chart1_AxisViewChanged(object sender, ViewEventArgs e)
    {
        if (e.Axis.AxisName == AxisName.X)
        {
            int start = (int)e.Axis.ScaleView.ViewMinimum;
            int end = (int)e.Axis.ScaleView.ViewMaximum;

            double[] temp = chart1.Series[0].Points.Where((x, i) => i >= start && i <= end).Select(x => x.YValues[0]).ToArray();
            double ymin = temp.Min();
            double ymax = temp.Max();

            chart1.ChartAreas[0].AxisY.ScaleView.Position = ymin;
            chart1.ChartAreas[0].AxisY.ScaleView.Size = ymax - ymin;
        }
    }


回答3:

Microsoft have made available a whole range of samples for download. In the sample application there is one called Scrollable Appearance that seems to do what you want.

Scrollable Appearance http://img502.imageshack.us/img502/5172/zoomablechart.png

The user can select and area of the graph and it will zoom in. They can also move around using the scroll bars.

C# Sample code is included with the download.