簡體   English   中英

使用ggplot顯示特定時間段的plot

[英]Show plot for specific time period with ggplot

我有納斯達克指數從 1985 年到 2022 年的數據,我想知道是否有可能在給定時期而不是整個時期顯示 plot。 那么從 1990 年到 2005 年?

這是我到目前為止編寫的代碼。

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()

當前圖

提前致謝。

答:您有兩種直接的方法:

  1. 在繪制到所需日期之前過濾數據集
  2. 在您的 plot 上,將x軸限制為所需的日期。 請注意,在這種方法中,您的字段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