r - 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()
解决方案
没有您的数据,我们无法完全复制,但这里尝试使用一些样本生成的数据,这些数据应该足够相似,您可以根据自己的目的进行调整。
# 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))
推荐阅读
- android - 具有 kotlin 库依赖的 Flutter 应用程序中的 NoClassDefFoundError
- php - MAMP:无法加载动态库“php_intl.dll”
- javascript - 单击电子商务网站中的搜索按钮后,如何阻止页面重新加载?
- c++ - 尝试在 Codeblocks 上使用 Boost 库会给出未定义的参考
- google-cloud-platform - GCE 提供的 OS 映像是 OS 的维护版本还是归档版本?
- rust - 'nightly' vs 'stable' Rust 或编译器版本的条件编译
- reactjs - React-Intl 在 FormatMessage 中包装子元素
- java - Java 并发实践“清单 7.1。使用 volatile 字段保持取消状态。”。同步可见性?
- c - C中的错误“表达式必须具有指向对象类型的指针”
- node.js - 将收到的“.xlsx”文件从 Laravel 应用程序传递到 Nextjs 前端 ui