我尝试通过 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;
}
}
最佳答案
一个常见的错误。
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
:
chart_dashboard.Series[yourSeries].XValueType = ChartValueType.DateTime;
要控制轴标签的显示方式,请设置其格式:
chart_dashboard[ChartAreas[0].AxisX.LabelStyle.Format = someDateTimeFormatString;
要创建像“Week 1”这样的字符串,您需要
- 将
XValueType
设置为int16
- 添加 x 值作为周数
- 将其格式化为
..axis.LabelStyle.Format = "Week #0";
从按空格和 Convert.ToInt16 拆分的数据中提取数字!
如果确实需要将稀疏 x 值作为字符串插入,则必须在系列中的每个间隙处插入一个dummy DataPoint
。
创建一个虚拟 DataPoint
很简单:
DataPoint dp = new DataPoint() { IsEmpty = true};
但是提前知道差距在哪里是一个挑战! “最好”的方法是在添加点之前检查数据并填写。或者稍后再检查它,而不是添加,而是在间隙处插入假人。两者都比首先获得正确的数据要麻烦得多!
关于c# - 添加的图表系列点与 X 轴不同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37934784/