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

Jac*_* Le 3 c# charts series highcharts

我尝试通过 C# 以表格为图片绘制图表。但是,正如您在日期中看到的 A4 数据:7 和 8/6 应该保持在相同的 7 和 8/6 X 轴上,此处异常所有这些都保留在 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;
            }
        }
Run Code Online (Sandbox Code Playgroud)

TaW*_*TaW 6

一个常见的错误。

string datetime = dataGridView1.Rows[i].Cells[2].Value.ToString();
Run Code Online (Sandbox Code Playgroud)

这是错误的!如果将 x 值添加为字符串,则它们都将添加为字符串,0并且Series无法将它们与 X 轴上的正确插槽对齐。所以它们从左到右依次添加..

而是简单地添加 x 值,因为DateTimes它们应该是!

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

DateTime datetime = (DateTime) dataGridView1.Rows[i].Cells[2].Value;
Run Code Online (Sandbox Code Playgroud)

如果没有,请将它们转换为 DateTime

DateTime datetime = Convert.ToDateTime(dataGridView1.Rows[i].Cells[2].Value);
Run Code Online (Sandbox Code Playgroud)

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

chart_dashboard.Series[yourSeries].XValueType = ChartValueType.DateTime;
Run Code Online (Sandbox Code Playgroud)

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

chart_dashboard[ChartAreas[0].AxisX.LabelStyle.Format = someDateTimeFormatString;
Run Code Online (Sandbox Code Playgroud)

要创建一个像“Week 1”这样的字符串,你会

  • 设置XValueTypeint16
  • 添加 x 值作为周数
  • 像这样格式化 ..axis.LabelStyle.Format = "Week #0";

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


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

创建一个虚拟对象DataPoint很简单:

 DataPoint dp = new DataPoint() { IsEmpty = true};
Run Code Online (Sandbox Code Playgroud)

提前知道差距哪里是挑战!“最好”的方法是在添加点之前检查数据并填写。或者稍后再检查它,而不是添加, 而是在间隙处插入假人。两者都比一开始​​就正确获取数据要麻烦得多!