我在这里发现了一个类似的问题,但答案并没有帮助我。我认为由于我的数据结构。iOS图表3 - 用阴谋对齐X标签(日期)
我有一个由各个数组组成的数组,每个数组都有自己的图表。然后这个多行结构构成该行的绘图点。
我的问题是值/行是正确的,但没有正确与日期对齐。在下面的例子中。日期从5月3日开始,5月8日结束。请帮助
这里是我的代码
struct chartPoint {
let date:String
var total:Double
let exercise:String
}
var sets:[[chartPoint]] = []
func setupLineChart() {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
var dataSets:[LineChartDataSet] = []
var color:[UIColor] = [UIColor.red,UIColor.blue, UIColor.green,UIColor.red,UIColor.red,UIColor.red,UIColor.red]
for i in sets { //Array of array of structs
let sort = i.sorted { // sort the internal array by date
item1, item2 in
let date1 = dateFormatter.date(from:item1.date)
let date2 = dateFormatter.date(from:item2.date)
return date1!.compare(date2!) == ComparisonResult.orderedAscending
}
var dataEntries: [ChartDataEntry] = []
for stat in 0...(sort.count - 1) {
let date = dateFormatter.date(from:sort[stat].date)
let timeIntervalForDate: TimeInterval = date!.timeIntervalSince1970
let dataEntry = ChartDataEntry(x: Double(timeIntervalForDate), y: sort[stat].total)
dataEntries.append(dataEntry)
if stat == (sort.count - 1){
let chartDataSet = LineChartDataSet(values: dataEntries, label: "\(sort[stat].exercise)")
chartDataSet.setCircleColor(color[stat])
chartDataSet.setColor(color[stat], alpha: 1.0)
chartDataSet.drawValuesEnabled = true
dataSets.append(chartDataSet)
startChart(dataSets: dataSets)
}
}
}
}
func startChart(dataSets:[LineChartDataSet]){
testLineChartView.animate(xAxisDuration: 0.7, yAxisDuration: 0.7)
testLineChartView.dragEnabled = true
testLineChartView.legend.form = .circle
testLineChartView.drawGridBackgroundEnabled = false
let xaxis = testLineChartView.xAxis
xaxis.valueFormatter = axisFormatDelegate
xaxis.labelCount = dataSets.count
xaxis.granularityEnabled = true
xaxis.granularity = 1.0
xaxis.centerAxisLabelsEnabled = true
xaxis.avoidFirstLastClippingEnabled = true
xaxis.drawLimitLinesBehindDataEnabled = true
let rightAxis = testLineChartView.rightAxis
rightAxis.enabled = false
let leftAxis = testLineChartView.leftAxis
leftAxis.drawZeroLineEnabled = true
leftAxis.drawGridLinesEnabled = true
axisFormatDelegate = self
testLineChartView.delegate = self
let chartData = LineChartData(dataSets: dataSets)
testLineChartView.data = chartData
testLineChartView.chartDescription?.text = ""
}
extension ChartViewController: IAxisValueFormatter {
func stringForValue(_ value: Double, axis: AxisBase?) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd MMM"
let date = Date(timeIntervalSince1970: value)
return dateFormatter.string(from: date)
}
}
这是不一样的(让x轴= testLineChartView.xAxis xaxis.valueFormatter = axisFormatDelegate)? – ThundercatChris
我已更新我的代码以显示设置。它基本上是一个具有绘图点阵列的数组,由结构数组组成。这样一条线可以在一个数组内有几个绘图点,而另一条线可以有它自己的。我希望这是有道理的 – ThundercatChris
我也尝试使用日期字符串数组(我认为这就是你所建议的),但他们又是错位。我不认为字符串是问题。它的抵消 – ThundercatChris