简体   繁体   English

使用ggplot显示特定时间段的plot

[英]Show plot for specific time period with ggplot

I have data for Nasdaq index from 1985 to 2022, I was wondering if it was possible to show a plot for a given period instead of whole.我有纳斯达克指数从 1985 年到 2022 年的数据,我想知道是否有可能在给定时期而不是整个时期显示 plot。 So from like 1990 to 2005?那么从 1990 年到 2005 年?

This is the code I have written so far.这是我到目前为止编写的代码。

Nasdaq19852022 %>%
ggplot(aes(x=Date,y=Close)) +
labs(title = "NASDAQ index prices",
   
   subtitle = "End of Month Index Prices",
   caption = " Source: Eikon") +

xlab("Date") + ylab("Total Return") +
scale_color_manual(values = c("Black"))+
geom_line()

当前图

Thanks in advance.提前致谢。

A: You have two straightforward approaches:答:您有两种直接的方法:

  1. Filter your dataset before plotting to the desired dates在绘制到所需日期之前过滤数据集
  2. On your plot, limit the x axis to the desired dates.在您的 plot 上,将x轴限制为所需的日期。 Note that on this approach, your field Date must be a date object.请注意,在这种方法中,您的字段Date必须是日期 object。
library(tidyBdE)
library(ggplot2)
# I use here the IBEX-35 Index (since you didn't provide your data)
ibex <- bde_series_load("254433", "Close")

ibex %>%
  ggplot(aes(x = Date, y = Close)) +
  labs(
    title = "IBEX index prices",
    subtitle = "End of Month Index Prices",
    caption = " Source: Bank of Spain"
  ) +
  xlab("Date") +
  ylab("Total Return") +
  scale_color_manual(values = c("Black")) +
  geom_line()

在此处输入图像描述

# First approach: Filter out the dataset
ibex %>%
  filter(Date >= "1990-01-01" & Date <= "2005-12-31") %>%
  ggplot(aes(x = Date, y = Close)) +
  labs(
    title = "IBEX index prices",
    subtitle = "End of Month Index Prices",
    caption = " Source: Bank of Spain"
  ) +
  xlab("Date") +
  ylab("Total Return") +
  scale_color_manual(values = c("Black")) +
  geom_line()

在此处输入图像描述

# Second approach: Filter the plot on the scales
# Same result
ibex %>%
  ggplot(aes(x = Date, y = Close)) +
  labs(
    title = "IBEX index prices",
    subtitle = "End of Month Index Prices",
    caption = " Source: Bank of Spain"
  ) +
  scale_x_date(limits = as.Date(c("1990-01-01", "2005-12-31"))) +
  xlab("Date") +
  ylab("Total Return") +
  scale_color_manual(values = c("Black")) +
  geom_line()

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM