C# 画图控件CHART 自定义坐标轴刻度标签

C# 画图控件chart –坐标轴刻度问题

 

项目中用到柱形图,当数据列比较多的时候, X轴的刻度标签会被精简为几个,无法在每个柱子下方显示其刻度值。这时候可以用自定义标签解决问题。

 

效果如图: 本例子,标签设置为时间字符串,要显示每个时间区间的统计图。

 

 

自定义标签的使用很简单(三步),如下,就可以把“8:30”字符串放到刻度1的位置.

                CustomLabellabel = new CustomLabel();

                label.Text = “8:30”;                

                label.ToPosition =1D;

               chart1.ChartAreas[0].AxisX.CustomLabels.Add(label);

 

需要注意的是, X坐标轴的数据类型,千万别设置为DateTime,否则标签不显示。

 

看完整代码如下 (建立一个WinForm工程,拖上chart控件,到Form1.Designer.cs中把serial1相关的代码去掉,我们在下面代码中创建数据系列1,2).

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;

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

        private void Form1_Load(object sender, EventArgs e)
        {
            Series s1 = new Series();
            Series s2 = new Series();
            Random r = new Random();
            for (int i = 1; i < 13; i++)
            {
                s1.Points.AddXY(i, r.Next(20, 30));
                s2.Points.AddXY(i, r.Next(10, 30));
            }
            chart1.Series.Add(s1);
            chart1.Series.Add(s2);
            chart1.ChartAreas[0].AxisX.MajorGrid.LineColor = Color.Green;
            DateTime t = DateTime.Parse("8:30");
            for (int i = 1; i < 26; i++)
            {
            if (i%2==1)
            {
                CustomLabel label = new CustomLabel();
                label.Text = t.ToShortTimeString() ;                 
                label.ToPosition =i;
                chart1.ChartAreas[0].AxisX.CustomLabels.Add(label);   
                label.GridTicks = GridTickTypes.Gridline;
                t = t.AddHours(1);  
            }

            }
            


        }
    }
}


 

  • 10
    点赞
  • 59
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值