r - 显示多个变量和几何图形的时间序列的 ggplot 图例
问题描述
我正在尝试向这个时间序列添加一个图例
并重命名图例中的每个 y 。我做了一些研究,但找不到适合我的例子。每个geom_
对应于我的 df_07 中的一列(仅包含整数)。
这是我的代码:
gg07 <-
ggplot(df_07) +
geom_line(aes(x = datetime, y = pred_pm25_monitor_humidity), color = "blue") +
geom_line(aes(x = datetime, y = pm25_monitor), linetype = "dashed") +
geom_point(aes(x = datetime, y = pm25 ), shape = 1) +
ylab("PM2.5 (µg/m3)") +
xlab("Date") +
ggtitle("Raw and Fitted Monitor Data -- July 01-08, 2020")
我正在尝试创建一个看起来像这样的图例:“蓝线”安装监视器 PM25
“虚线”监视器 PM25 “空圆圈”传感器 PM25
太感谢了!
解决方案
当您遇到更复杂的图例时,我发现 ggplot 通常最终会与您作对。这是基于常规绘图功能的解决方案:
## Create some fake data
set.seed(100)
x <- seq( 1,8, length.out=25*7 )
base.curve <- 10*(dnorm(x, mean=3.5, sd=.2) +
dnorm(x, mean=5.2, sd=.1) +
dnorm(x, mean=5.5, sd=2 )*3
)
library(lubridate)
a <- approx(
c( ymd_hms('2020-07-01T00:00:00'), ymd_hms('2020-07-08T00:00:00') ),
n = length(x)
)
x.date <- as_datetime(a$y)
pm25 <- base.curve + rnorm(length(x),sd=.4)
pm25_monitor_humidity <- base.curve^.7*.9
pm25_monitor <- pm25_monitor_humidity+rnorm(n=length(x),sd=.4)
dr <- range(x.date)
date.at <- seq(dr[1], dr[2], by="day")[seq(2,8,2)]
## Plot it:
plot( x.date, pm25, xaxt="n", type="n" )
axis( 1, at=date.at, format(date.at,"%b %d") )
points( x=x.date, y=pm25, cex=.7 )
lines( x=x.date, y=pm25_monitor_humidity, col="blue" )
lines( x=x.date, y=pm25_monitor, lty="dashed" )
## Legend:
labels <- c(
"Sensor PM25","Fitted monitor PM25","Monitor PM25"
)
legend(
"right",
legend = labels,
pch=c(1,NA,NA),
lty=c(NA,"solid","dashed"),
col=c("black","blue","black")
)
推荐阅读
- java - 将韩文(韩文)字母分解成元素?
- amazon-cloudformation - Whatsapp 商业 API HTTPS 证书
- javascript - 来自带有 Next.js 的 getStaticProps 的无效响应
- ios - prefersStatusBarHidden iOS 13 未调用
- reactjs - 我可以从 Component Did Mount 访问状态吗
- regex - 防止正则表达式跳过中间的值
- python - 如何绘制以时间序列为行的 Pandas 数据框?
- cakephp - CakePHP 3.x 翻译行为:使用“get”读取所有翻译
- python - 枚举来自源节点的 DAG 中的所有路径,仅访问一次
- javascript - Chrome 重新加载页面的方式与预期不同