iOS Charts库柱状图动态条目仅反转(升序)后可正常显示问题
我使用的图表库来自 Charts
第三方API会生成按从新到旧降序排列的图表用JSON数据(格式为年份:数量)。
当我尝试按API返回的降序顺序填充BarChartDataEntries时,X轴标签仍保持升序排列,同时出现如下异常空列:
而当我将数据反转后填充,图表显示就全部正常了。
问题原因
- iOS Charts库的X轴默认按照
BarChartDataEntry的x属性的数值升序排布刻度,entry的添加顺序不影响它在X轴上的实际位置,x参数本身才是对应X轴坐标的核心依据。 - 接口返回的是降序排列的年份数据,直接填充时,X轴会自动计算最小到最大的年份区间,按升序展示刻度,此时entry的x值顺序和X轴刻度顺序不匹配,就会出现空列错位的问题。
- 反转数据后entry的x值变为升序,刚好匹配X轴默认的升序逻辑,因此显示恢复正常。
可选解决方案
方案1:保持现有反转数据的逻辑
如果产品需求是X轴按年份升序展示(更早的年份在左侧),可以直接启用代码中注释的反转写法即可,无需额外调整其他配置,是成本最低的方案:
for i in (0..<statistics.count).reversed() {
方案2:X轴按降序展示(最新年份在左侧)
如果需要保留接口返回的降序展示逻辑,不用反转数据,只需在X轴配置代码块中添加一行配置即可:
barChartView.xAxis.reverse = true
该配置会将X轴的刻度排列顺序反转,自动适配降序的年份数据,不会出现空列问题。
调整后的完整参考代码:
override func viewDidLoad() { super.viewDidLoad() statisticServices.getStatistics() { _ in self.setBarChart(statistics) } } private func setBarChart(_ statistics: [Statistics]){ var ordinEntries: [BarChartDataEntry] = [] // 无需反转,直接按接口返回的降序填充 for i in 0..<statistics.count { guard let dosarYear = Double(statistics[i].dosarYear), let totalCount = Double(statistics[i].successCount) else { print("No statistic data for the chart") return } let dataEntry = BarChartDataEntry( x: dosarYear, y: totalCount, data: statistics[i] ) ordinEntries.append(dataEntry) } let chartData = BarChartData() let dataSet = BarChartDataSet(entries: ordinEntries) dataSet.highlightColor = NSUIColor(cgColor: redColor.cgColor) dataSet.highlightAlpha = 1.0 dataSet.barBorderWidth = 0 dataSet.valueFont = UIFont(name: "Rockwell", size: 9)! dataSet.colors = [NSUIColor(cgColor: blueColor.cgColor)] chartData.addDataSet(dataSet) barChartView.data = chartData barChartView.delegate = self barChartView.legend.enabled = false barChartView.gridBackgroundColor = NSUIColor.white barChartView.rightAxis.enabled = false barChartView.leftAxis.gridLineDashLengths = [4,4] barChartView.leftAxis.gridColor = UIColor.rgb(0xc6c6c6) barChartView.leftAxis.labelFont = UIFont(name: "Rockwell", size: 9)! barChartView.xAxis.drawGridLinesEnabled = false barChartView.xAxis.labelPosition = XAxis.LabelPosition.bottom barChartView.xAxis.granularityEnabled = true barChartView.doubleTapToZoomEnabled = false barChartView.xAxis.granularity = 1 // 新增X轴反转配置 barChartView.xAxis.reverse = true barChartView.setVisibleXRangeMaximum(6.0) barChartView.animate(xAxisDuration: 1.0, yAxisDuration: 1.0) }
内容的提问来源于stack exchange,提问作者AlexF
相关产品推荐
相关产品推荐

