【问题标题】:How do you draw a straight line tangent to smoothed curve in R?你如何在R中绘制一条与平滑曲线相切的直线?
【发布时间】:2020-10-20 09:02:49
【问题描述】:

我正在尝试从原点(或 Y 轴上的任何点)绘制一条与黄土曲线相切的直线(一条仅与曲线接触一次的线)。

The black line is the smoothed curve of the points, and I wish to draw that yellow line.

我将发布我的代码以获得下面的平滑曲线。

'''

library(quantmod)
library(plotly)
library(PerformanceAnalytics)
library(timetk)
library(tidyverse)

ticker = c('AMZN', 'AAPL', 'NFLX', 'XOM', 'T')
price_data = getSymbols(ticker, from = '2014-01-01', to = '2018-05-31')

prices = do.call(cbind,
                 lapply(ticker, function(x) Ad(get(x))))

rets = Return.calculate(prices, method = 'log') %>%
  na.omit()
    
num_port = 1000
all_wts = matrix(nrow = num_port, ncol = length(ticker))
port_returns = vector('numeric', length = num_port)
port_risk = vector('numeric', length = num_port)
port_sr = vector('numeric', length = num_port)

for (i in seq_along(port_returns)) {
  
  wts = runif(n = length(ticker))
  wts = wts/sum(wts)
  
  all_wts[i,] = wts
  
  port = Return.portfolio(R = rets, weights = wts, verbose = TRUE)
  
  a = StdDev.annualized(port$returns)[1]
  b = SharpeRatio.annualized(port$returns, Rf = 0)[1]
  c = a*b
  
  port_returns[i] = c
  port_risk[i] = a
  port_sr[i] = b

}

all_wts = tk_tbl(all_wts)
colnames(all_wts) = colnames(rets)

pf_val = tibble(ret = port_returns, risk = port_risk, sr = port_sr)
pf_val = tk_tbl(cbind(all_wts, pf_val))

min_var = pf_val[which.min(pf_val$risk),]
max_sr = pf_val[which.max(pf_val$sr),]

library(tidyverse)

pf_line2 = pf_val[which((pf_val$ret %in% d$ret)),]


p3 = ggplot(aes(x = risk, y = ret, color = sr), data = pf_line2) +
  geom_point() + theme_classic() +
  scale_y_continuous(labels = scales::percent) +
  scale_x_continuous(labels = scales::percent) +
  labs(x = 'risk', y = 'return') +
  geom_smooth(method = 'loess', col='black', level=0.5, alpha=0.1)
  

ggplotly(p3)

'''

【问题讨论】:

  • 我不知道任何与此相关的 ggplot 函数 - 但我的直觉是获取黄土多项式并取导数(在某一点)得到一条切线。根据您的示例,黄土很有可能会返回一条看起来不像 2 次多项式的曲线。在这种情况下,选择一个切线点显然很重要。

标签: r ggplot2 loess


【解决方案1】:

我尝试运行您的数据,但代码中未定义 d,因此无法重现您的示例。

如果您知道这些尺寸,则可以使用 geom_abline 添加一条具有自己的截距和斜率的线。

ggplot(aes(x = wt, y = mpg), data = mtcars) +
geom_point()+
labs(x = 'wt', y = 'mpg') +
geom_abline(intercept = 10, slope = 6)+
geom_smooth(method = 'loess', col='black', level=0.5, alpha=0.1)

这给了这样的东西。 line with geom_smooth.

我不是一个完整的专家,但我希望这能在某种程度上有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 2019-02-27
    • 1970-01-01
    相关资源
    最近更新 更多