WPF LiveChart图表Y轴显示小数及坐标轴标签缺失问题求助
解决LiveChart图表的两个问题
问题1:X/Y轴标签不显示
你当前把员工名称设为每个ColumnSeries的Title,这只会让名称显示在图例里,而非X轴标签。正确做法是将员工名称集合作为X轴的Labels,同时为X/Y轴设置明确的标题。
问题2:Y轴显示小数
需要配置Y轴的格式化器,强制只输出整数,并确保刻度步长为整数单位。
修改后的完整代码
// "Stats" button handling the Employees Performances private void ButtonThird_Click(object sender, RoutedEventArgs e) { MainTitle.Content = "Employee Performances"; CollaspAllView(); DataTable dt = new DataTable(); string connString = "Server=localhost;Port=3306;User ID=root;Database=barberdb"; string query = "SELECT s.staff_id, s.staff_name, COUNT(a.appointment_id) AS appointment_count FROM appointment a JOIN staff s ON a.staff_id = s.staff_id GROUP BY s.staff_id, s.staff_name ORDER BY s.staff_id"; try { using (MySqlConnection conn = new MySqlConnection(connString)) { MySqlCommand cmd = new MySqlCommand(query, conn); conn.Open(); MySqlDataAdapter adapter = new MySqlDataAdapter(cmd); adapter.Fill(dt); } } catch (Exception ex) { MessageBox.Show("An error occurred: " + ex.Message); } SeriesCollection seriesCollection = new SeriesCollection(); List<string> staffLabels = new List<string>(); ChartValues<int> appointmentCounts = new ChartValues<int>(); // 整合所有员工数据到单个系列和标签集合 foreach (DataRow row in dt.Rows) { string staffName = row["staff_name"].ToString(); int numAppointments = Convert.ToInt32(row["appointment_count"]); staffLabels.Add(staffName); appointmentCounts.Add(numAppointments); } // 创建单个柱状图系列,对应所有员工的预约数 seriesCollection.Add(new ColumnSeries { Title = "预约数量", Values = appointmentCounts, DataLabels = true, LabelPoint = chartPoint => string.Format("{0:N0}", chartPoint.Y) }); // 绑定图表所需的所有数据(系列、标签、轴标题、格式化器) DataContext = new { SeriesCollection = seriesCollection, StaffLabels = staffLabels, XAxisTitle = "员工姓名", YAxisTitle = "预约数量", YAxisFormatter = new Func<double, string>(value => value.ToString("N0")) }; Stats.Visibility = Visibility.Visible; }
配套XAML配置
需要在Stats区域的LiveChart控件中添加轴的配置,确保标签和格式化规则生效:
<lvc:CartesianChart Series="{Binding SeriesCollection}"> <lvc:CartesianChart.AxisX> <lvc:Axis Title="{Binding XAxisTitle}" Labels="{Binding StaffLabels}" /> </lvc:CartesianChart.AxisX> <lvc:CartesianChart.AxisY> <lvc:Axis Title="{Binding YAxisTitle}" LabelFormatter="{Binding YAxisFormatter}" /> </lvc:CartesianChart.AxisY> </lvc:CartesianChart>
关键说明
- 之前的代码为每个员工创建独立
ColumnSeries,导致X轴显示系列索引而非员工名称;改为单个系列+Labels集合的方式,X轴会正确展示员工姓名。 - Y轴通过
LabelFormatter绑定格式化方法,使用"N0"格式字符串强制输出整数,彻底解决小数显示问题。
内容的提问来源于stack exchange,提问作者Musta_Jaguaari
相关产品推荐
相关产品推荐

