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

如何在Julia中向Plots.OHLC函数正确传递DataFrame数据?

解决Plots.OHLC函数的MethodError问题

问题描述

尝试将Excel读取的DataFrame数据传递给Plots.OHLC绘制K线图时,遇到以下错误:

ERROR: MethodError: no method matching Plots.OHLC(::Vector{Any}, ::Vector{Any}, ::Vector{Any}, ::Vector{Any}, ::Vector{Any})

当前DataFrame各列的数据类型均为Any:

DataType[Any, Any, Any, Any, Any]

原代码如下:

using Dates
using XLSX
using Plots
using DataFrames

# Load data from Excel file
data = DataFrame(XLSX.readtable("Janeiro2023.xlsx", "Sheet1"))

# Check data types of columns
println(eltype.(eachcol(data)))

# Extract the columns as arrays
datetime_array = data[!, 1]
open_array = data[!, 2]
high_array = data[!, 3]
low_array = data[!, 4]
close_array = data[!, 5]

# Create an OHLC object from the arrays
ohlc = Plots.OHLC(datetime_array, open_array, high_array, low_array, close_array)

# Plot the candlestick chart
plot(ohlc)

解决方案

Plots.OHLC对参数类型有明确要求:时间列需为AbstractVector{<:TimeType}(如DateTime),价格列需为AbstractVector{<:Real}(如Float64),需将DataFrame的列从Any转换为对应类型:

  1. 转换列数据类型
    使用transform!批量处理列类型,需根据Excel中数据的实际格式调整:

    # 转换时间列:假设时间格式为"yyyy-mm-dd HH:MM:SS",根据你的数据修改格式字符串
    transform!(data, 1 => ByRow(x -> DateTime(x, "yyyy-mm-dd HH:MM:SS")) => 1)
    # 转换2-5列的价格数据为Float64
    transform!(data, 2:5 => ByRow.(x -> parse(Float64, x)) => 2:5)
    

    如果Excel中时间已是标准日期格式,可简化为:

    transform!(data, 1 => ByRow(DateTime) => 1)
    transform!(data, 2:5 => ByRow(Float64) => 2:5)
    
  2. 验证转换结果
    再次检查列类型,确认不再是Any:

    println(eltype.(eachcol(data)))
    
  3. 修改后完整代码
    转换完成后,再提取数组传递给Plots.OHLC即可正常运行:

    using Dates
    using XLSX
    using Plots
    using DataFrames
    
    # Load data from Excel file
    data = DataFrame(XLSX.readtable("Janeiro2023.xlsx", "Sheet1"))
    
    # Convert column types
    transform!(data, 1 => ByRow(x -> DateTime(x, "yyyy-mm-dd HH:MM:SS")) => 1)
    transform!(data, 2:5 => ByRow.(x -> parse(Float64, x)) => 2:5)
    
    # Check data types of columns
    println(eltype.(eachcol(data)))
    
    # Extract the columns as arrays
    datetime_array = data[!, 1]
    open_array = data[!, 2]
    high_array = data[!, 3]
    low_array = data[!, 4]
    close_array = data[!, 5]
    
    # Create an OHLC object from the arrays
    ohlc = Plots.OHLC(datetime_array, open_array, high_array, low_array, close_array)
    
    # Plot the candlestick chart
    plot(ohlc)
    

注意事项

  • 若时间列转换失败,检查Excel中时间的实际格式,调整DateTime的格式字符串参数
  • 若价格列包含非数值内容,需先清洗数据(如处理空值、异常字符)再转换

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 18:27:33