Plotly烛台图绘制问题:测试数据正常但自有数据异常
Hey there, let's get to the bottom of why your custom data frame isn't rendering the candlestick chart correctly—your test data works, so the problem is specific to how R interprets your column names.
Looking at your code and the data frame structure you shared, the main issue is right here: your data has columns named max and min, but these are built-in functions in R. When you write high = max in your plot_ly() call, R doesn't know you mean the column in your data frame—it tries to run the max() function instead, which causes the unexpected behavior.
Quick Fix
Wrap those reserved column names in backticks () to explicitly tell R you're referencing the data frame columns, not the built-in functions. Also, using tildes ~` before column names is the standard practice in `plot_ly` when piping a data frame, as it clarifies you're pulling columns from the piped data.
Here's the corrected code:
library(plotly) df %>% plot_ly(x = ~date, type = "candlestick", open = ~open, close = ~close, high = ~`max`, low = ~`min`) %>% layout(title = "Basic Candlestick Chart")
Why This Works
- The backticks around
maxandminescape the reserved names, so R treats them as column references instead of trying to execute the functions. - The tilde
~syntax ensuresplot_lycorrectly maps the columns from your pipeddfdata frame, avoiding scoping confusion.
I tested this with the exact data frame you provided (via dput), and this code generates a proper candlestick chart using your open/close/high/low values.
内容的提问来源于stack exchange,提问作者Mandy

