如何使用C#在MSChart中设置x轴的值

7

我有这些XY值:

Series S1 = new Series()
S1.Points.AddXY(9, 25);
S1.Points.AddXY(10, 35);
S1.Points.AddXY(11, 15);
chart1.Series.Add(S1);

但是我需要在图表中显示如下形式的X值:

X="9-10"

X="10-11"

X="11-12"

我该如何实现呢?


到目前为止,这就是我找到的:

图表

这是代码:

private void Form1_Shown(object sender, EventArgs e)
    {
        chart1.ChartAreas[0].AxisX.Minimum = 7;
        chart1.ChartAreas[0].AxisX.Maximum = 15;

        Series S1 = new Series();
        S1.Points.AddXY(9, 25);
        S1.Points.AddXY(10, 35);
        S1.Points.AddXY(11, 15);
        chart1.Series.Add(S1);

        chart1.Series[0].Points[0].AxisLabel = "9-10";
        chart1.Series[0].Points[1].AxisLabel = "10-11";
        chart1.Series[0].Points[2].AxisLabel = "11-12";

正如您所看到的,我处理数字,并为X轴标签设置文本,但我只能针对DataPoints值进行操作,我需要对整个数值范围进行操作。

有什么想法吗?

2个回答

7

感谢sipla的回答:

使用自定义标签和定制事件:

string[] range = new string[10];

    private void Form1_Shown(object sender, EventArgs e)
    {
        chart1.ChartAreas[0].AxisX.Minimum = 7;
        chart1.ChartAreas[0].AxisX.Maximum = 16;

        range[0] = "";
        range[1] = "7-8";
        range[2] = "8-9";
        range[3] = "9-10";
        range[4] = "10-11";
        range[5] = "11-12";
        range[6] = "12-1";
        range[7] = "1-2";
        range[8] = "2-3";
        range[9] = "";

        Series S1 = new Series();            
        S1.Points.AddXY(9, 25);
        S1.Points.AddXY(10, 35);
        S1.Points.AddXY(11, 15);
        chart1.Series.Add(S1);            

    }

    int count;
    private void chart1_Customize(object sender, EventArgs e)
    {
        count = 0;
        foreach (CustomLabel lbl in chart1.ChartAreas[0].AxisX.CustomLabels)
        {
            lbl.Text = range[count];
            count++;
        }                        
    }

Graph


3

你可能好奇为什么你的范围数组是那样展开的。更好的方法是使用定义和初始化时的方括号,这样会更加清晰。例如:

string[] range = new string[10] {"","7-8","8-9","9-10","10-11","11-12","12-1","1-2","2-3",""};
/*
  The tenth element is also likely unnecessary 
  as it simply repeats the first     
  element of the array
*/

是的,这很有道理。 - Somebody

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接