首页 > 解决方案 > plotting sine and cosine with charts have kinks

问题描述

I use this changed code from another user to plot sine and cosine 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"
        }

But the my graph does not look good, because as you can see the resulting grah has some kinks.

enter image description here

What can I do to smooth the graph of non-linear functions ? Thanks in advance.

标签: iosswiftchartsios-charts

解决方案


这里:

    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,但图表库只能为你做这么多的平滑。这条线不是魔法。

为了使曲线更平滑,我们可以使用更多更接近的 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)) }

推荐阅读