You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift使用Core Plot时如何给图表添加数值并绘制f(x)=x²+10函数?

Core Plot 绘制 f(x)=x²+10 实现方案

实现步骤

  • 配置绘图空间的坐标范围,按需求将x轴、y轴的显示范围都设置为0~100
  • 创建散点图实例(CPTScatterPlot),配置线条样式、标识等绘制属性
  • 实现绘图数据源协议,按固定步长采样x值,计算对应f(x)的y值作为绘图数据源
  • 将散点图添加到已初始化的graph对象中完成渲染

注意:f(x)=x²+10在x≈9.48时y值就已经达到100,所以x超过9.48的部分会超出y轴显示范围,不会在画布上渲染。如果需要完整显示x在0~100区间的函数曲线,可以自行调高y轴的上限值。


完整代码示例

你需要先让当前控制器遵守CPTPlotDataSource协议,然后在原有初始化代码后补充如下逻辑:

// 原有初始化代码
let graph = CPTXYGraph(frame: hostview.bounds)
hostview.hostedGraph = graph
graph.paddingLeft = 0.0
graph.paddingTop = 0.0
graph.paddingRight = 0.0
graph.paddingBottom = 0.0
graph.axisSet = nil

// 新增配置代码开始
// 1. 配置坐标范围
guard let plotSpace = graph.defaultPlotSpace as? CPTXYPlotSpace else { return }
// x轴范围0~100
plotSpace.xRange = CPTPlotRange(location: 0, length: 100)
// y轴范围0~100
plotSpace.yRange = CPTPlotRange(location: 0, length: 100)

// 2. 配置曲线样式
let linePlot = CPTScatterPlot()
linePlot.dataSource = self
// 设置线条样式:红色、线宽2pt
let lineStyle = CPTMutableLineStyle()
lineStyle.lineWidth = 2
lineStyle.lineColor = .red()
linePlot.dataLineStyle = lineStyle

// 3. 将曲线添加到绘图对象
graph.add(linePlot)

数据源方法实现

在当前控制器中添加如下CPTPlotDataSource协议方法:

// 返回采样点总数:x从0到9.5、步长0.1,共96个点保证曲线平滑
func numberOfRecords(for plot: CPTPlot) -> UInt {
    return UInt(96)
}

func plot(_ plot: CPTPlot, numberFor field: UInt, recordAt idx: UInt) -> NSNumber? {
    let x = Double(idx) * 0.1
    switch field {
    case 0: // 对应X轴数值
        return NSNumber(value: x)
    case 1: // 对应Y轴数值,按f(x)=x²+10计算
        let y = pow(x, 2) + 10
        return NSNumber(value: y)
    default:
        return nil
    }
}

内容的提问来源于stack exchange,提问作者Gabriel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 11:45:04