[英]How to plot multiple time series (common x-axis with vertical facet) using Plot in R?
I am trying to plot a Vertical stack plot for 4 time series in R. The following codes can show the figure, but the 'lty' and 'col' parameters are not working correctly.我正在尝试 plot R 中的 4 个时间序列的垂直堆栈 plot。以下代码可以显示该图,但 'lty' 和 'col' 参数无法正常工作。 Meanwhile, although "main=NULL" is used, the title still shows.
同时,虽然使用了“main=NULL”,但标题仍然显示。 Is there any way to fix this?
有没有什么办法解决这一问题?
In addition, is there any way to set the "xlim" for each small plot?另外,有没有办法为每个小plot设置“xlim”? Thank you.
谢谢你。
data(UKgas)
ts1 = UKgas
ts2 = UKgas+100
ts3 = UKgas+500
ts4 = UKgas+1000
plot(ts.union(TS1 = ts1, TS2 = ts2,TS3 = ts3, TS4 = ts4), lty = 1:4, col = 1:4, main = NULL)
Plotting a ts.union
object calls the method stats:::plot.ts
, and from looking at the source code, this will only take a single color I'm afraid.绘制
ts.union
object 调用方法stats:::plot.ts
,从查看源代码来看,这恐怕只会采用一种颜色。 You can get the result you want using a little data wrangling and ggplot2
, with the added benefit that the plot is fully customizable.您可以使用一些数据争论和
ggplot2
获得您想要的结果,另外一个好处是 plot 是完全可定制的。
library(ggplot2)
library(tidyr)
ts_s <- ts.union(TS1 = ts1, TS2 = ts2,TS3 = ts3, TS4 = ts4)
times <- attr(ts_s, "tsp")
df <- cbind(as.data.frame(ts_s), year = seq(times[1], times[2], 1/times[3]))
ggplot(pivot_longer(df, 1:4), aes(year, value, colour = name)) +
geom_line(aes(linetype = name)) +
scale_x_continuous(breaks = seq(1960, 1985, 5)) +
facet_grid(name~., switch = "y", scales = "free_y") +
labs(title = NULL) +
theme_classic() +
theme(panel.background = element_rect(color = "black"),
strip.placement = "outside",
strip.background = element_blank(),
panel.spacing.y = unit(0, "npc"),
strip.text = element_text(size = 16, face = 2),
legend.position = "none")
Created on 2022-03-13 by the reprex package (v2.0.1)由reprex package (v2.0.1) 创建于 2022-03-13
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.