简体   繁体   中英

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. So from like 1990 to 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. Note that on this approach, your field Date must be a 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()

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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