用对数刻度绘制R(ggplot2)中的海峡线?

时间:2018-01-10 19:51:55

标签: r logging ggplot2

好的,所以我正在尝试(并且没有)重现显示标准普尔500指数长期市场趋势的情节。

因为我以对数刻度显示y轴的图,所以连接线是弯曲的。我希望他们是海峡。叹了口气,但我失败了!

Log scale of S&P 500

代码:

SP500.1950 <- read.csv("SP1950.csv")
colnames(SP500.1950) <- "Price"
SP500.1950 <- xts(SP500.1950[,-1], order.by=as.Date(SP500.1950[,1]))
SP500 <- get.Quantmod.Yahoo(symbol = "^GSPC",startDate = "1900-12-31")
SP500 <- SP500[endpoints(SP500,on = "months"),]
colnames(SP500) <- "Price"

SP500 <- rbind(SP500.1950,SP500) 
colnames(SP500) <- "Price"



x10 <- SP500[index(SP500) == "1900-01-01",]
x10[1,1] = 8.21
x10 <- rbind(x10,SP500[index(SP500) == "1922-04-01",])
x10 <- rbind(x10,SP500[index(SP500) == "1929-09-01",])
x10 <- rbind(x10,SP500[index(SP500) == "1932-07-01",])
x10 <- rbind(x10,SP500[index(SP500) == "1937-02-01",])
x10 <- rbind(x10,SP500[index(SP500) == "1950-04-28",])
x10 <- rbind(x10,SP500[index(SP500) == "1966-02-28",])
x10 <- rbind(x10,SP500[index(SP500) == "1978-10-31",])
x10 <- rbind(x10,SP500[index(SP500) == "2000-03-31",])
x10 <- rbind(x10,SP500[index(SP500) == "2013-01-31",])
SP500.max <- subset(SP500, as.Date(index(SP500)) > as.Date("2009-03-2009"))
x20 <- period.max(SP500.max[,1],endpoints(SP500.max))
x10 <- rbind(x10,x20[nrow(x20),])



#2013-01-31
  gg.sp500sc <- ggplot(SP500,aes(x=as.Date(index(SP500)),y = SP500[,1])) + 
    theme_minimal() + 
    theme() + 
    geom_line()+
    geom_line(data = x10, aes(x = as.Date(index(x10)),y=x10[,1]), color = "blue",size = 1) + 
    ggtitle("S&P 500 Index Secular Chart") + 
    coord_trans(y = "log") +
    xlab("") + 
    xlab("")
  gg.sp500sc

有关快速修复的想法吗?

干杯, Sody

修改

感谢您的帮助,结果如下: complete picture

1 个答案:

答案 0 :(得分:1)

问题是在统计变换之后发生坐标变换,这会改变宝石的出现方式。尝试将coord_trans(y = "log")替换为scale_y_continuous(trans = "log")。这是一个可重复的小例子:

library(dplyr)
library(ggplot2)

set.seed(888)

d <- data_frame(
  x = 1:1000,
  y = x + 10 + rnorm(1000)
)

d2 <- filter(d, x %in% c(50, 500))

ggplot(d, aes(x = x, y = y)) +
  geom_line() +
  geom_line(data = d2, color = "blue") +
  scale_y_continuous(trans = "log")