在斯威夫特的图表堆积条形图

时间:2016-04-10 07:56:39

标签: swift charts ios-charts

我正在尝试使用我的iOS项目中的Charts框架(Swift)构建堆积条形图。我现在所能建立的只是一个分组的条形图。有人知道怎么做吗?

我找到的只有:Convert bar chart to a grouped bar chart with danielgindi/ios-charts and Swift

这是我的代码:

@IBOutlet var barChartView: BarChartView!
var receivedDate1 : String = ""
var receivedDate2 : String = ""
var receivedDate3 : String = ""
var receivedDate4 : String = ""
var receivedDate5 : String = ""

var months: [String]!

override func viewDidLoad() {
    super.viewDidLoad()

    months = [receivedDate1, receivedDate2, receivedDate3, receivedDate4, receivedDate5]
    let dominanz1 = [1.0, 2.0, 3.0, 4.0, 5.0]
    let dominanz2 = [5.0, 4.0, 3.0, 2.0, 1.0]

    setChartBarGroupDataSet(months, values: dominanz1, values2: dominanz2, sortIndex: 1)

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func setChartBarGroupDataSet(dataPoints: [String], values: [Double], values2: [Double],sortIndex:Int) {

    var dataEntries: [BarChartDataEntry] = []
    var dataEntries2: [BarChartDataEntry] = []


    for i in 0..<dataPoints.count {

        let dataEntry = BarChartDataEntry(value: values[i], xIndex: i)
        dataEntries.append(dataEntry)
    }


    for i in 0..<dataPoints.count {

        let dataEntry = BarChartDataEntry(value: values2[i], xIndex: i)
        dataEntries2.append(dataEntry)
    }


    let chartDataSet = BarChartDataSet(yVals: dataEntries, label: " ")
    let chartDataSet2 = BarChartDataSet(yVals: dataEntries2, label: " ")

    chartDataSet2.colors =  [UIColor(red: 255/255, green: 70/255, blue: 108/255, alpha: 1)]

    chartDataSet.colors =  [UIColor(red: 49/255, green: 27/255, blue: 146/255, alpha: 1)]


    let dataSets: [BarChartDataSet] = [chartDataSet,chartDataSet2]

    let data = BarChartData(xVals: dataPoints, dataSets: dataSets)

    barChartView.data = data

    barChartView.descriptionText = ""


    barChartView.rightAxis.drawGridLinesEnabled = false
    barChartView.rightAxis.drawAxisLineEnabled = false
    barChartView.rightAxis.drawLabelsEnabled = false


    barChartView.animate(xAxisDuration: 2.0, yAxisDuration: 2.0, easingOption: .EaseInBounce)


}

我使用的框架是cocoapods的图表2.2.4。 这就是目前的情况:grouped bar chart 这就是它应该是这样的:stacked bar chart

1 个答案:

答案 0 :(得分:1)

准备BarchartDataEntry,在yAxis中有两个值,如

let months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]

let unitsSold = [20.0, 4.0, 6.0, 3.0, 12.0, 16.0, 4.0, 18.0, 2.0, 4.0, 5.0, 4.0]

let unitsBought = [10.0, 14.0, 60.0, 13.0, 2.0, 1.0, 5.0, 1.0, 12.0, 14.0, 15.0, 14.0]

let dataEntry = BarChartDataEntry(x: Double(i), yValues:  [self.unitsSold[i],self.unitsBought[i]], label: "groupChart")


 var dataEntries: [BarChartDataEntry] = []
 for i in 0..<self.months.count {
            let dataEntry = BarChartDataEntry(x: Double(i) , y: self.unitsSold[i])
            dataEntries.append(dataEntry)
}