ios - 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.
What can I do to smooth the graph of non-linear functions ? Thanks in advance.
解决方案
这里:
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)) }
推荐阅读
- android - 查找 NavHostFragment Jetpack Navigation Android 时出错
- java - 为什么@RequestParam 注释绑定请求正文中的值?
- react-native - react native 第三方方法不会覆盖或实现超类型中的方法
- sql - Rails:使用选择连接
- c# - 无法在c#中拆分字符串
- javascript - Excel 16.13 中的 Office js 对话框问题
- python - Python jupyter库导入错误
- python - 编辑表单中另一个模型的 Django Admin 过滤器
- python - 按值将文件中的数字附加到列表中
- java - 在 Apahce commons VFS 中连接不同的域