用图表绘制正弦和余弦有缺陷

时间:2019-06-17 13:30:56

标签: ios swift charts ios-charts

我使用了另一个用户更改的代码来绘制正弦和余弦iOS Charts, wavy lines

import UIKit
import Charts

class ViewController: UIViewController, ChartViewDelegate{

    var lineChartView: LineChartView!

    override func viewDidLoad() {


        lineChartView = LineChartView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height))
        lineChartView?.delegate = self
        self.view.addSubview(lineChartView!)

        let ys1 = Array(0..<10).map { x in return sin(Double(x)) }
        let ys2 = Array(0..<10).map { x in return cos(Double(x)) }

        let yse1 = ys1.enumerated().map { x, y in return ChartDataEntry(x: Double(x), y: y) }
        let yse2 = ys2.enumerated().map { x, y in return ChartDataEntry(x: Double(x), y: y) }

        let data = LineChartData()
        let ds1 = LineChartDataSet(entries: yse1, label: "Hello")
        ds1.colors = [NSUIColor.red]
        ds1.drawCirclesEnabled = false
        ds1.drawValuesEnabled = false
        ds1.mode = .cubicBezier
        data.addDataSet(ds1)

        let ds2 = LineChartDataSet(entries: yse2, label: "World")
        ds2.colors = [NSUIColor.blue]
        ds2.drawCirclesEnabled = false
        ds2.drawValuesEnabled = false
        ds2.mode = .cubicBezier
        data.addDataSet(ds2)
        self.lineChartView.data = data

        self.viewChart.gridBackgroundColor = NSUIColor.white

        self.lineChartView.chartDescription?.text = "Linechart Demo"
        }

但是我的图看起来不好,因为您可以看到生成的grah有一些纽结。

enter image description here

我该怎么做才能平滑非线性函数的图? 提前致谢。

1 个答案:

答案 0 :(得分:2)

这里:

    let ys1 = Array(0..<10).map { x in return sin(Double(x)) }
    let ys2 = Array(0..<10).map { x in return cos(Double(x)) }

    let yse1 = ys1.enumerated().map { x, y in return ChartDataEntry(x: Double(x), y: y) }
    let yse2 = ys2.enumerated().map { x, y in return ChartDataEntry(x: Double(x), y: y) }

您仅使用10个值。曲线不平滑也就不足为奇了。即使您正在执行ds1.mode = .cubicBezier,但Charts库也只能为您做很多平滑处理。这行不是魔术。

为使曲线更平滑,我们可以使用更靠近的sin(x)和cos(x)的更多值。让我们使用0到10之间的100个值,而不是10,每次使用0.1的步长。

let ys1 = Array(0..<100).map { x in ChartDataEntry(x: Double(x) / 10, y: sin(Double(x) / 10)) }
let ys2 = Array(0..<100).map { x in ChartDataEntry(x: Double(x) / 10, y: cos(Double(x) / 10)) }