Reputation: 55
I trying to use Charts, but i can't display each month on X axis, only through one. Look at picture.
In stringForValue
i tried to print value and it's show : 0 2 4 6 8 10 0 1 2 3 4 5 6 7 8 9 10 11 0 2 4 6 8 10
But why it's passed three time which first and last time through one? What can i do for displaying each month?
import UIKit
import Charts
class BarChartViewController: UIViewController {
var months = [String]()
var unitsSold = [Double]()
weak var axisFormatDelegate: IAxisValueFormatter?
@IBOutlet weak var barChartView: BarChartView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
axisFormatDelegate = self
months = ["Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
]
unitsSold = [1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0,11.0,12.0]
setChart(dataPoints: months, values: unitsSold)
}
func setChart(dataPoints: [String], values: [Double]) {
barChartView.noDataText = "NO DATA"
var dataEntries = [BarChartDataEntry]()
for i in 0..<dataPoints.count {
let dataEntry = BarChartDataEntry(x: Double(i), y: values[i], data: dataPoints)
dataEntries.append(dataEntry)
}
let chartDataSet = BarChartDataSet(entries: dataEntries, label: "Units Sold")
let chartData = BarChartData(dataSet: chartDataSet)
barChartView.data = chartData
barChartView.xAxis.valueFormatter = axisFormatDelegate
}
}
extension BarChartViewController: IAxisValueFormatter {
func stringForValue(_ value: Double, axis: AxisBase?) -> String {
print(Int(value))
return months[Int(value)]
}
}
Upvotes: 3
Views: 2249
Reputation: 2161
You have at least two options to solve your problem.
Just set property labelCount
for xAxis, e.g. barChartView.xAxis.labelCount = 12
.
Or user method setLabelCount(:)
, e.g. barChartView.xAxis.setLabelCount(12, force: true)
.
Pay your attention that using property labelCount
does not guarantee that the number of labels will exactly equal to specified by you.
Upvotes: 1