由于某种原因,我的两个数据集相互叠加,而堆栈如下所示。例如星期一应该总共22个星期三应该总共6个。
我创建了两个数据集,因为我希望改变每个数据集的颜色:
let chartDataSet1 = BarChartDataSet(values: dataEntries1, label: "Points")
chartDataSet1.barBorderColor = .gray
let chartDataSet2 = BarChartDataSet(values: dataEntries2, label: "Scans")
chartDataSet2.barBorderColor = .red
...
class ViewController: UIViewController {
@IBOutlet weak var barChartView: BarChartView!
override func viewDidLoad() {
super.viewDidLoad()
barChartView.descriptionText = ""
barChartView.xAxis.labelPosition = .bottom
let ll = ChartLimitLine(limit: 10.0, label: "Target")
barChartView.rightAxis.addLimitLine(ll)
setChart()
}
func setChart(){
let months = ["Mon", "Tues", "Wed", "Thu", "Fri", "Sat", "Sun"]
let points = [20.0, 4.0, 3.0, 6.0, 12.0, 16.0, 4.0]
let scans = [2.0, 4.0, 3.0, 6.0, 2.0, 4.0, 2.0]
barChartView.setBarChartData(xValues: months, yValues1: scans, yValues2: points)
}
}
...
extension BarChartView {
func setBarChartData(xValues: [String], yValues1: [Double], yValues2 : [Double]) {
var dataEntries1: [BarChartDataEntry] = []
var dataEntries2: [BarChartDataEntry] = []
for i in 0..<yValues1.count {
let dataEntry1 = BarChartDataEntry(x: Double(i), yValues: [yValues1[i]], label: "Points")
// let dataEntry = BarChartDataEntry(x: Double(i), y: yValues[i])
dataEntries1.append(dataEntry1)
}
for i in 0..<yValues2.count {
let dataEntry2 = BarChartDataEntry(x: Double(i), yValues: [yValues2[i]], label: "Scans")
// let dataEntry = BarChartDataEntry(x: Double(i), y: yValues[i])
dataEntries2.append(dataEntry2)
}
let chartDataSet1 = BarChartDataSet(values: dataEntries1, label: "Points")
chartDataSet1.barBorderColor = .gray
let chartDataSet2 = BarChartDataSet(values: dataEntries2, label: "Scans")
chartDataSet2.barBorderColor = .red
let chartData = BarChartData(dataSets: [chartDataSet1, chartDataSet2])
let chartFormatter = BarChartFormatter(labels: xValues)
let xAxis = XAxis()
xAxis.valueFormatter = chartFormatter
self.xAxis.valueFormatter = xAxis.valueFormatter
self.data = chartData
}
}
如果我将chartDataSet1和chartDataSet2合并到一个数组中,条形图会正确堆叠,但我无法弄清楚如何更改每个数据的颜色:
答案 0 :(得分:3)
您必须像这样设置条形图数据:
extension BarChartView {
func setBarChartData(xValues: [String], yValues1: [Double], yValues2 : [Double]) {
var dataEntries1: [BarChartDataEntry] = []
for i in 0..<yValues1.count {
let dataEntry1 = BarChartDataEntry(x: Double(i), yValues: [yValues1[i], yValues2[i]], label: "Points")
dataEntries1.append(dataEntry1)
}
let chartDataSet1 = BarChartDataSet(values: dataEntries1, label: "Points")
chartDataSet1.barBorderColor = .red
chartDataSet1.stackLabels = ["Points", "Scans"]
chartDataSet1.colors = [UIColor.darkGray, UIColor.lightGray]
let chartData = BarChartData(dataSets: [chartDataSet1])
let chartFormatter = BarChartFormatter(labels: xValues)
let xAxis = XAxis()
xAxis.valueFormatter = chartFormatter
self.xAxis.valueFormatter = xAxis.valueFormatter
self.data = chartData
}
}