【问题标题】:Adjusting the plot axis automatically in R在 R 中自动调整绘图轴
【发布时间】:2021-04-04 12:45:05
【问题描述】:

我正在分析捕获多年信息的历史股票价格数据。作为分析的一部分,我想挑选出较短的时间段,并通过枢轴点绘制直线,即通过高点和低点,出现在股票图表上。

有人可以分享一个 R 中的脚本示例,它会自动调整 y 和 x 轴以拉伸和加宽或压缩它们,从而导致通过枢轴点绘制的直线的斜率等于 1或 -1(即 y=x 或 y=-x)?

我已尝试搜索解决方案,但找不到任何提供自动调整轴的方法。如果可能的话,我希望计算机确定如何调整轴以实现 Y 轴上价格单位的变化与 X 轴上时间单位的变化相比的统一变化。谢谢

# =============================================
# Clear environment
# =============================================
rm(list=ls())
# =============================================


# =============================================
# Load packages
# =============================================
if (!require("cwhmisc")) install.packages("cwhmisc")
library( cwhmisc )

if (!require("BatchGetSymbols")) install.packages("BatchGetSymbols")
library( BatchGetSymbols )
# =============================================


# =============================================
# inflect function
# =============================================
inflect <- function(x, threshold = 1){
  up   <- sapply(1:threshold, function(n) c(x[-(seq(n))], rep(NA, n)))
  down <-  sapply(-1:-threshold, function(n) c(rep(NA,abs(n)), x[-seq(length(x), length(x) - abs(n) + 1)]))
  a    <- cbind(x,up,down)
  list(minima = which(apply(a, 1, min) == a[,1]), maxima = which(apply(a, 1, max) == a[,1]))
}

# =============================================
# Set dates
# =============================================
W1.date <- as.Date("2020-01-03") # Whole Range Start Date
W2.date <- as.Date("2020-02-22") # Whole Range End   Date
# =============================================

# =============================================
frequency <- 'daily' # set frequency
ticker    <- "PBR"   # set ticker
# =============================================


# =============================================
# Pull out data from Yahoo
# =============================================
l.out <- BatchGetSymbols(tickers = ticker, 
                         first.date   = W1.date,
                         last.date    = W2.date, 
                         freq.data    = frequency,
                         cache.folder = file.path(tempdir(), 'BGS_Cache') ) # cache in tempdir()
# =============================================
#l.out
#names(l.out)
#names(l.out$df.tickers)
# =============================================


# =============================================
# Create Whole Range dataframe
# =============================================
sDF <- as.data.frame(l.out$df.tickers)
#Check# sDF
# =============================================


# =============================================
# Pick a desired threshold # to plot up to
# =============================================
n <- 2
# Generate Data
# randomwalk <- 100 + cumsum(rnorm(50, 0.2, 1)) # climbs upwards most of the time
randomwalk <- sDF$price.close

bottoms <- lapply(1:n, function(x) inflect(randomwalk, threshold = x)$minima)
tops    <- lapply(1:n, function(x) inflect(randomwalk, threshold = x)$maxima)
# Color functions
cf.1 <- grDevices::colorRampPalette(c("pink","red"))
cf.2 <- grDevices::colorRampPalette(c("cyan","blue"))
par(mar=c(1,1,1,1))
plot(randomwalk, type = 'l', main = "Minima & Maxima\nVariable Thresholds")
for(i in 1:n){
  points(bottoms[[i]], randomwalk[bottoms[[i]]], pch = 16, col = cf.1(n)[i], cex = i/1.5)
}
for(i in 1:n){
  points(tops[[i]], randomwalk[tops[[i]]], pch = 16, col = cf.2(n)[i], cex = i/1.5)
}
legend("topleft", legend = c("Minima",1:n,"Maxima",1:n), 
        pch = rep(c(NA, rep(16,n)), 2), col = c(1, cf.1(n),1, cf.2(n)), 
        pt.cex =  c(rep(c(1, c(1:n) / 1.5), 2)), cex = .75, ncol = 2)
# 
bottoms
tops

【问题讨论】:

  • 如果你能分享一些样本数据会很好,也许还能更好地说明你正在尝试做什么。
  • 此时意图很明确,但缺少示例数据,很难知道您从哪里开始。您是否确定了“枢轴点”和模型?或者您是从需要帮助检测这些点并围绕它的数据子集的大数据集开始的?如果您以有效的 R 语法向我们提供良好的输入,那么帮助您变得很容易。没有这些,帮助您的第一步就变成了“猜测您的数据是什么样子”。
  • 三种共享数据的好方法:(1) 使用内置数据集,(2) 在数据对象上使用dput(),您必须共享它的副本/可粘贴版本,例如,dput(your_data[1:20, ]) 用于your_data 的前 20 行,(3) 共享代码以模拟假数据(使用 set.seed(),因此任何随机性都是可重现的!)。
  • 我已经添加了上面的代码。其中包含数据的来源,它来自雅虎,代码为“PBR”,从 2020 年 1 月 2 日到 2020 年 2 月 22 日。谢谢

标签: r plot charts stock


【解决方案1】:

我相信您正在寻找的功能如下:

coord_fixed(ratio = 1)

这是 ggplot 包的一个函数部分,您可以为其设置一个比率,在这种情况下您需要 1。可以提供其他参数以将其设置为从 0 等开始。

文档可以在这里找到:

https://ggplot2.tidyverse.org/reference/coord_fixed.html

我在下面的可重现示例中写了一个使用它的快速示例。

library(tidyverse)

# Construct generic data
x = 1:100
y = rep(2, 100)

df <- tibble(x = x, y= y)

# Plot incorrect graph
df %>% 
  ggplot(aes(x = x, y = y)) +
  geom_line() +
  geom_abline(intercept = 0, linetype = 2, color = "red") +
  ylim(c(0, 200))


# Plot graph with x, y axis 1:1
df %>% 
  ggplot(aes(x = x, y = y)) +
  geom_line() +
  coord_fixed(ratio = 1) +
  geom_abline(intercept = 0, linetype = 2, color = "red") +
  ylim(c(0, 200))

reprex package (v2.0.0) 于 2021-04-04 创建

【讨论】:

  • 感谢您的出色解决方案,非常感谢您的建议,并且肯定会使用此功能。我使用的是雅虎历史股票数据,它基本上是每日收盘价,通过股票图表上的枢轴点绘制直线会导致这些线的斜率在 0 到 180 度之间。有没有办法在调整 x 和 y 轴之前首先确定这个初始斜率或线的角度是多少?然后我希望基于该确定使用 coord_fixed 对轴进行调整。再次感谢
  • 如果我理解正确,您根本不需要设置 x 和 y 轴限制,我这样做是为了说明形状的变化。如果您想要 y=x,则固定的 Co-Ord 应始终为 1。如果您希望 y=x 线处于不同的角度,是否可以澄清您如何知道您想要的角度?
  • 如果我要通过上图所示的上枢轴点画线,在这种情况下,它通常没有 45 度或实际上 135 度的斜率。我想让脚本自动调整 X 和 Y 轴,以便股票图表被拉伸或挤压,这样会导致通过枢轴点绘制的这条特定直线的斜率实际上与斜率一致-1 或 135 度,无论初始坡度是从什么开始的。为此,我需要能够让脚本确定初始范围或角度
  • 我看到 coord_fixed 是多么有用,我只是希望能够让脚本分析这条直线的初始角度/斜率,然后让它调整 x 和 y 轴以达到 45度斜率。再次对此的想法将不胜感激。
  • 如果你的线有方程 y = mx + c,那么你会将比率设置为 m 以表示固定的坐标我相信(但当 m = 0 时你可能要小心) .
猜你喜欢
  • 1970-01-01
  • 2012-07-27
  • 1970-01-01
  • 1970-01-01
  • 2012-10-04
  • 2015-06-02
  • 1970-01-01
  • 1970-01-01
  • 2018-03-28
相关资源
最近更新 更多