当我尝试您的代码时(请注意,这是在 R studio 的 R 3.1.0 中),y 轴数字比例似乎没有被切断。不过,您可以调整chart_pars()(正如您已经部分完成的那样)和chart_theme() 来实现您想要的。
要减少 y 轴上的拥挤,您可以调整 chart_pars() 的边距参数 $mar。增加左(和或右)边距参数值以消除 y 轴数字的拥挤。您还可以考虑删除左侧或右侧 y 轴刻度以节省更多空间。这是一个示例,并附有说明:
library(quantmod)
getSymbols("SPY", from="2013-11-01", to=Sys.Date())
myPars <- chart_pars()
myPars$mar <- c(3, 2, 0, .2) # default is c(3, 1, 0, 1) # bottom, left, top, right
myPars$cex <- 1.5 #' Increase font size of both x and y axis scale ticks
mychartTheme <- chart_theme()
mychartTheme$rylab = FALSE #' Don't show y-axis on right side of plot to save space
# mychartTheme$lylab = TRUE #' Show y-axis ticks on left side of plot? Default is TRUE for both left and right sides.
chart1 <- chart_Series(SPY, pars=myPars, theme = mychartTheme)
chart1
你将从这段代码中得到的情节是:
此外,如果您有兴趣编辑显示在 y 轴刻度数字上的小数位数(例如,在 FX 中以 1e-4 点为单位报价的货币),您可以在以下位置编辑 chart_Series 的源代码某些行来得到你想要的。
例如,仅在 LEFT y 轴上绘制到小数点后 4 位,并将 y 轴数字的打印偏移到左侧(因此它们不会绘制在靠近绘图左边距的条形下方),您可以像这样编辑 chart_Series 的第 143-147 行(通过以下编辑创建 chart_Series 的副本):
#' my.chart_Series is identical to the definition of chart_Series, with these minor edits
my.chart_Series <- function (x, name = deparse(substitute(x)), type = "candlesticks",
subset = "", TA = "", pars = chart_pars(), theme = chart_theme(),
clev = 0, ...)
{
cs <- new.replot()
....
[lines 143-147]: if (theme$lylab) {
cs$add(expression(text(1 - 1/3 - max(strwidth(alabels)),
alabels, sprintf("%.4f", alabels), #alabels, noquote(format(alabels, justify = "left", digits = 4)),
col = theme$labels, offset = -2, cex = 0.9, pos = 4,
xpd = TRUE)), expr = TRUE)
} #' default offset = 0
....
}
然后在你的 R 脚本中看到这个效果写这样的东西:
source('my.chart_Series.R')
environment(my.chart_Series) <- environment(get("chart_Series", envir = asNamespace("quantmod")))
assignInNamespace(x = "chart_Series", value = my.chart_Series, ns = "quantmod")
myPars <- chart_pars()
myPars$mar <- c(3, 3, 0, .2) # default is c(3, 1, 0, 1) # bottom, left, top, right
myPars$cex <- 1.0 #' Increase font size of both x and y axis scale ticks
mychartTheme <- chart_theme()
mychartTheme$rylab = FALSE #' Don't show y-axis on right side of plot to save space
# mychartTheme$lylab = TRUE #' Show y-axis ticks on left side of plot? Default is TRUE for both left and right sides.
chart1 <- quantmod:::chart_Series(SPY, pars=myPars, theme = mychartTheme) #' Note the need to prepend the quantmod namespace to the modified visible chart_Series function in quantmod.
chart1
这会给你这个情节:
另外,为了减少在 y 轴上绘制的刻度数,您还可以修改 chart_Series 中的第 128 行,如下所示:
p <- pretty(ylim, n = 5) #' The original source code (quantmod 0.4-0) is p <- pretty(ylim, 10)
有关 R 函数 pretty 中 n 参数的约束,请参阅 R 帮助文档。这给出了: