首页 > 解决方案 > ggplot2 上是否有与 points() 等价的东西

问题描述

我正在研究股票价格并试图绘制价格差异。我使用创建了一个autoplot.zoo(),我的问题是,当它们高于上限阈值时,如何将点形状更改为三角形,而当它们低于下限阈值时,如何将它们更改为圆形。我知道在使用基本plot()函数时,你可以通过调用points()函数来完成这些,想知道我怎么能做到这一点,但使用ggplot2.

这是情节的代码:

p<-autoplot.zoo(data, geom = "line")+
        geom_hline(yintercept = threshold, color="red")+
        geom_hline(yintercept = -threshold, color="red")+
        ggtitle("AAPL vs. SPY out of sample")
p+geom_point()

情节形象

标签: rggplot2plot

解决方案


没有您的数据,我们无法完全复制,但这里尝试使用一些样本生成的数据,这些数据应该足够相似,您可以根据自己的目的进行调整。

# Sample data
data = data.frame(date = c(2001:2020),
                  spread = runif(20, -10,10))

# Upper and lower threshold
thresh <- 4

您可以根据数据本身的关系创建一个确定形状的附加变量,并将其作为参数传递给 ggplot。

# Create conditional data
data$outlier[data$spread > thresh] <- "Above"
data$outlier[data$spread < -thresh] <- "Below"
data$outlier[is.na(data$outlier)] <- "In Range"

library(ggplot2)
ggplot(data, aes(x = date, y = spread, shape = outlier, group = 1)) +
  geom_line() +
  geom_point() +
  geom_hline(yintercept = c(thresh, -thresh), color = "red") +
  scale_shape_manual(values = c(17,16,15))

在此处输入图像描述

# If you want points just above and below# Sample data
data = data.frame(date = c(2001:2020),
                  spread = runif(20, -10,10))
thresh <- 4
data$outlier[data$spread > thresh] <- "Above"
data$outlier[data$spread < -thresh] <- "Below"
ggplot(data, aes(x = date, y = spread, shape = outlier, group = 1)) +
  geom_line() +
  geom_point() +
  geom_hline(yintercept = c(thresh, -thresh), color = "red") +
  scale_shape_manual(values = c(17,16))

在此处输入图像描述

或者,您可以将高于和低于阈值的点添加为具有手动指定形状的单独图层,如下所示。pch参数指向形状类型。

# Another way of doing this

data = data.frame(date = c(2001:2020),
                  spread = runif(20, -10,10))

# Upper and lower threshold
thresh <- 4

ggplot(data, aes(x = date, y = spread, group = 1)) +
  geom_line() +
  geom_point(data = data[data$spread>thresh,], pch = 17) +
  geom_point(data = data[data$spread< (-thresh),], pch = 16) + 
  geom_hline(yintercept = c(thresh, -thresh), color = "red") +
  scale_shape_manual(values = c(17,16))

在此处输入图像描述


推荐阅读