你如何在R中绘制一条与平滑曲线相切的直线?

How do you draw a straight line tangent to smoothed curve in R?

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

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

我将post我的代码来获得下面的平滑曲线。

'''

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)

'''

我试过 运行 你的数据,但 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.

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