我正在尝试在Charts中添加日期/字符串作为xAxis标签(标签之间必须有相等的间距)
我正在下面做,但构造函数中的x只期望有一个double。
有什么主意吗?
for i in 0..<self.grahEntries.count {
let x1 = self.grahEntries[i].x
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "YYY-MM-DD HH:mm:ss"
let date = dateFormatter.date(from: x1)
print(date)
let dataEntry = ChartDataEntry(x: date, y: self.grahEntries[i].y)//HERE IS MY PROBLEM!! xAxis is only double
dataEntries.append(dataEntry)
}
let line1 = LineChartDataSet(values: dataEntries, label: "Units Consumed")
line1.colors = [NSUIColor.blue]
line1.mode = .cubicBezier
line1.cubicIntensity = 0.2
let gradient = getGradientFilling()
line1.fill = Fill.fillWithLinearGradient(gradient, angle: 90.0)
line1.drawFilledEnabled = true
let data = LineChartData()
data.addDataSet(line1)
mChart.data = data
mChart.setScaleEnabled(false)
mChart.animate(xAxisDuration: 1.5)
mChart.xAxis.valueFormatter = DateAxisValueFormatter()
mChart.xAxis.granularity = 1.0
mChart.drawGridBackgroundEnabled = false
mChart.xAxis.drawAxisLineEnabled = false
mChart.xAxis.drawGridLinesEnabled = false
mChart.leftAxis.drawAxisLineEnabled = true
mChart.leftAxis.drawGridLinesEnabled = true
mChart.rightAxis.drawAxisLineEnabled = false
mChart.rightAxis.drawGridLinesEnabled = false
mChart.legend.enabled = false
mChart.xAxis.enabled = true
mChart.leftAxis.enabled = true
mChart.rightAxis.enabled = false
mChart.xAxis.labelPosition = .bottom
mChart.xAxis.drawLabelsEnabled = true
mChart.xAxis.drawLimitLinesBehindDataEnabled = true
mChart.xAxis.avoidFirstLastClippingEnabled = true
更新:
答案 0 :(得分:0)
您已经发现,您需要使用双精度(或数值)作为x的值。在此之前,我已经根据日期绘制了此图,我的方法是使用自纪元以来的秒数将日期转换为数字,并使用:-
date.timeIntervalSince1970 / secondsPerDay
其中(足够准确):-
let secondsPerDay = 24.0 * 3600.0
要为查看器的轴上的日期设置格式,我将使用以下格式器:-
class DateAxisValueFormatter : NSObject, IAxisValueFormatter
{
let dateFormatter = DateFormatter()
override init()
{
super.init()
dateFormatter.dateFormat = "dd MMM"
}
func stringForValue(_ value: Double, axis: AxisBase?) -> String
{
let date = Date(timeIntervalSince1970: value * secondsPerDay)
return dateFormatter.string(from: date)
}
}
将我用过的值转换回正确的文本。如果您设置
lineChart.xAxis.valueFormatter = DateAxisValueFormatter()
lineChart.xAxis.granularity = 1.0
那么您只会在底部看到几天。
总而言之:
答案 1 :(得分:0)
如果您希望数据均匀分布(即不代表准确的时间轴),那么答案就比较简单。
将您的for
循环更改为
var dates: [String] = []
for i in 0..<self.grahEntries.count {
let x1 = self.grahEntries[i].x
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "YYY-MM-DD HH:mm:ss"
let date = dateFormatter.date(from: x1)
dates.append(date)
let dataEntry = ChartDataEntry(x: Double(i), y: self.grahEntries[i].y)
dataEntries.append(dataEntry)
}
并更改
mChart.xAxis.valueFormatter = DateAxisValueFormatter(dates)
然后更改DataAxisValueFormatter
以在构造函数中接受字符串数组并将其存储。更改
func stringForValue(_ value: Double, axis: AxisBase?) -> String
{
let i = Int(value)
return dates[i]
}