图表系列点添加不与X轴同步

我尝试通过C#绘制图表,表格为图片。 但是,正如您可以看到日期中的A4数据:7和8/6应保持相同的7和8/6 X轴,这里exception所有它们都留到5和6/6 X轴。 你能帮我解决一下吗?

在此处输入图像描述

for (int i = 0; i < 14; i++) { string productname = dataGridView1.Rows[i].Cells[0].Value.ToString(); string datetime = dataGridView1.Rows[i].Cells[2].Value.ToString(); int para = Convert.ToInt16(dataGridView1.Rows[i].Cells[1].Value); if (chart_dashboard.Series.IndexOf(productname) != -1) { chart_dashboard.Series[productname].Points.AddXY(datetime, para); chart_dashboard.ChartAreas[0].AxisX.Interval = 1; } else { chart_dashboard.Series.Add(productname); chart_dashboard.Series[productname].Points.AddXY(datetime, para); chart_dashboard.ChartAreas[0].AxisX.Interval = 1; } } 

一个常见的错误。

 string datetime = dataGridView1.Rows[i].Cells[2].Value.ToString(); 

这是错的! 如果将x值添加为字符串,则它们都将添加为0 ,而Series不能将它们与X轴上的正确插槽对齐。 所以他们从左到右顺序添加..

而只需将x值添加为它们应该是的DateTimes

因此,如果Cells包含DateTime值,请使用:

 DateTime datetime = (DateTime) dataGridView1.Rows[i].Cells[2].Value; 

如果他们不这样做,将它们转换为DateTime

 DateTime datetime = Convert.ToDateTime(dataGridView1.Rows[i].Cells[2].Value); 

要控制x值类型, XValueType为每个系列设置XValueType

 chart_dashboard.Series[yourSeries].XValueType = ChartValueType.DateTime; 

要控制轴标签的显示方式,请设置其格式:

 chart_dashboard[ChartAreas[0].AxisX.LabelStyle.Format = someDateTimeFormatString; 

要创建像“第1周”这样的字符串,你会

  • XValueType设置为int16
  • 将x值添加为周数
  • 将其格式化为..axis.LabelStyle.Format = "Week #0";

从空间和Convert.ToInt16中分割数据中的数字!


如果确实需要将稀疏x值作为字符串插入,则必须在系列的每个间隙处插入虚拟 DataPoint

创建虚拟DataPoint很简单:

  DataPoint dp = new DataPoint() { IsEmpty = true}; 

但是要知道差距哪里是挑战! “最佳”方式是在添加点之前检查数据并填写。 或者稍后再讨论,而不是添加 dummys 插入间隙。 两者都比首先获取数据要困难得多!