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);
}
}
}
}
}