StackedColumn堆叠柱形图出现间隙且Y轴数值不从0开始的问题求助
StackedColumn堆叠柱形图异常修复方案
问题表现
渲染堆叠柱形图时存在两处异常:
- 柱体之间存在非预期间隙
- Y轴数值未从0开始
修复方案
Y轴起始值异常修复
Chart控件默认会根据数据最大值自动适配Y轴最小刻度,手动指定Y轴最小值为0即可:
Chart1.ChartAreas[0].AxisY.Minimum = 0;
柱体间隙异常修复
间隙产生的核心原因是不同食物系列绑定的X轴区域ID数量不一致,部分区域下无对应食物数据时会缺省留空。需要先提取全量区域ID,每个食物系列按统一的区域ID顺序匹配数值,缺失值补0,保证所有系列的X轴维度完全对齐。
修正后完整代码
string query = "SELECT * FROM TBL_SAMPLE INNER JOIN TBL_AREA ON TBL_SAMPLE.AREA = TBL_AREA.AREA"; DataTable dt = GetData(query); // 提取全量、有序的区域ID列表,作为所有系列统一的X轴维度 List<int> allAreaIds = (from p in dt.AsEnumerable() select p.Field<int>("AREA_ID")).Distinct().OrderBy(id => id).ToList(); // 提取去重的食物列表(原代码变量名countries为笔误,已修正为foodList) List<string> foodList = (from p in dt.AsEnumerable() select p.Field<string>("FOOD")).Distinct().ToList(); foreach (string food in foodList) { Series foodSeries = new Series(food); foodSeries.IsValueShownAsLabel = true; foodSeries.ChartType = SeriesChartType.StackedColumn; // 按全量区域ID顺序匹配数值,缺失数据补0 List<int> yValues = new List<int>(); foreach (int areaId in allAreaIds) { var matchRow = dt.AsEnumerable().FirstOrDefault(p => p.Field<string>("FOOD") == food && p.Field<int>("AREA_ID") == areaId); yValues.Add(matchRow == null ? 0 : matchRow.Field<int>("TOTAL")); } // 绑定对齐后的X、Y轴数据 foodSeries.Points.DataBindXY(allAreaIds, yValues); Chart1.Series.Add(foodSeries); } // 强制Y轴从0开始 Chart1.ChartAreas[0].AxisY.Minimum = 0; Chart1.Legends[0].Enabled = true;
内容的提问来源于stack exchange,提问作者Alexander Constantine Rodrigue
相关产品推荐
相关产品推荐

