【问题标题】:chart x-axis numbering图表 x 轴编号
【发布时间】:2017-06-04 09:19:00
【问题描述】:

我正在使用 WinForms 图表来可视化一些数据。我想要我指定的点处的 x 轴网格线。请看下面的例子。

public partial class Form1: Form
{
    public Form1()
    {
        InitializeComponent();            
        AddPoints();
    }

    public void AddPoints()
    {
        for (int i = 0; i <= 100; i++)
            chart1.Series[0].Points.AddXY(i, i);
    }
}

在图表中,您可以看到 X 轴的网格线出现在 19、39、59、79 和 99。但我希望它出现在 0、15、45、65、90、100。你可以清楚地看到间隔是不一样的。所以设置间隔是没有用的。是否可以在我自己的指定点有网格线?

【问题讨论】:

    标签: c# winforms charts


    【解决方案1】:

    GridLines 无法做到这一点,因为它们将始终以固定的Interval 间距绘制。这是一个通过在xxxPaint 事件中绘制线条来解决问题的示例。

    首先,我们为我们想要的GridLines 声明一个停止值列表:

    List<double> stops = new List<double>();
    

    然后我们准备图表:

    AddPoints();
    
    ChartArea ca = chart1.ChartAreas[0];
    ca.AxisX.Minimum = 0;  // optional
    ca.AxisX.MajorGrid.Enabled = false;
    ca.AxisX.MajorTickMark.Enabled = false;
    ca.AxisX.LabelStyle.Enabled = false;
    
    stops.AddRange(new[] { 0, 15, 45, 50.5, 65, 90, 100 });
    

    请注意,我添加了一个额外的值 (50.5) 来展示我们如何绘制GridLines,即使在没有DataPoints 的地方!

    然后我们编码PostPaint事件:

    private void chart1_PostPaint(object sender, ChartPaintEventArgs e)
    {
        Graphics g = e.ChartGraphics.Graphics;
        g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;
    
        ChartArea ca = chart1.ChartAreas[0];
    
        Font font = ca.AxisX.LabelStyle.Font;
        Color col = ca.AxisX.MajorGrid.LineColor;
        int padding = 10; // pad the labels from the axis
    
        int y0 = (int)ca.AxisY.ValueToPixelPosition(ca.AxisY.Minimum);
        int y1 = (int)ca.AxisY.ValueToPixelPosition(ca.AxisY.Maximum);
    
        foreach (int sx  in stops)
        {
            int x = (int)ca.AxisX.ValueToPixelPosition(sx);
    
            using (Pen pen = new Pen(col))
                g.DrawLine(pen, x, y0, x, y1);
    
            string s =  sx + "";
            if (ca.AxisX.LabelStyle.Format != "") 
                s = string.Format(ca.AxisX.LabelStyle.Format, s);
    
            SizeF sz = g.MeasureString(s, font, 999);
            g.DrawString(s, font, Brushes.Black, (int)(x - sz.Width / 2) , y0 + padding);
    }
    

    这是结果:

    注意PostPaint事件中的大部分代码只是准备;线条和标签的两个实际绘图调用是普通的GDI+ 方法..

    请注意,我在循环中的每 10 个点添加了DataPoint 标签以显示我们所处的位置:

    chart1.Series[0].Points.AddXY(i, i);
    if (i%10 == 0) chart1.Series[0].Points[i].Label = "#VAL / #VALY";
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-26
      • 2016-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-27
      • 1970-01-01
      • 2018-06-24
      相关资源
      最近更新 更多