如何制作“折线图”和“条形图”的组合图表?

时间:2017-03-20 23:37:19

标签: swift3 xcode8 ios10 ios-charts

我找到了swift2的方法,但无法制作swift3。任何人都可以帮我制作这些组合图表的swift3代码吗?

我找到了这些代码:

 months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
    unitsSold = [20.0, 4.0, 6.0,20.0, 4.0, 6.0,20.0, 4.0, 6.0,20.0, 4.0, 6.0]
    databozi =  [10.0, 11.0, 12.0,10.0, 11.0, 12.0,10.0, 11.0, 12.0,10.0, 11.0, 12.0]


func convertCombines(dataEntryX forX:[String],dataEntryY forY: [Double], dataEntryZ forZ: [Double]) {


    var dataEntries = [BarChartDataEntry]()
    var dataEntrieszor = [ChartDataEntry]()


    for i in 0..<forX.count {

        dataEntries.append(BarChartDataEntry(x: forZ[i], y: Double(i)))
        dataEntrieszor.append(ChartDataEntry(x: forY[i], y: Double(i)))

    }
    let lineChartSet = LineChartDataSet(values: dataEntrieszor, label: "Line Data")
    let lineChartData = LineChartData(dataSets: [lineChartSet])

    let barChartSet = BarChartDataSet(values: dataEntries, label: "Bar Data")
    let barChartData = BarChartData(dataSets: [barChartSet])

    //ui
    lineChartSet.setColor(UIColor.red)
    lineChartSet.setCircleColor(UIColor.red)

    let comData = CombinedChartData(dataSets: [lineChartSet,barChartSet])
    comData.barData = barChartData
    comData.lineData = lineChartData

    combinedChartViewOut.data = comData
    combinedChartViewOut.notifyDataSetChanged()

}

我的示例代码图片 my Example code pic 但是

需要代码如下: Example Combined pic

1 个答案:

答案 0 :(得分:2)

修复代码:

func convertCombines(dataEntryX forX:[String],dataEntryY forY: [Double], dataEntryZ forZ: [Double]) {


    var dataEntries: [BarChartDataEntry] = []
    var dataEntrieszor: [ChartDataEntry] = [ChartDataEntry]()

    for (i, v) in forY.enumerated() {
        let dataEntry = ChartDataEntry(x: Double(i), y: v, data: forX as AnyObject?)
        dataEntrieszor.append(dataEntry)
    }

    for (i, v) in forZ.enumerated() {
        let dataEntry = BarChartDataEntry(x: Double(i), y: v, data: forX as AnyObject?)
        dataEntries.append(dataEntry)
    }


    let lineChartSet = LineChartDataSet(values: dataEntrieszor, label: "Line Data")
    let lineChartData = LineChartData(dataSets: [lineChartSet])

    let barChartSet = BarChartDataSet(values: dataEntries, label: "Bar Data")
    let barChartData = BarChartData(dataSets: [barChartSet])

    //ui
    lineChartSet.setColor(UIColor.red)
    lineChartSet.setCircleColor(UIColor.red)

    let comData = CombinedChartData(dataSets: [lineChartSet,barChartSet])
    comData.barData = barChartData
    comData.lineData = lineChartData

    combinedChartViewOut.data = comData
    combinedChartViewOut.notifyDataSetChanged()

    combinedChartViewOut.xAxis.valueFormatter = IndexAxisValueFormatter(values:months)
    combinedChartViewOut.xAxis.granularity = 1

    combinedChartViewOut.animate(xAxisDuration: 2.0, yAxisDuration: 2.0, easingOption: .easeInCirc)


}