R语言 如何在ggplot2中仅显示x轴范围内的一些日期

93ze6v8z  于 2022-12-06  发布在  其他
关注(0)|答案(1)|浏览(149)

当我绘制图表时,它是不可读的,因为在数据中的所有日期都写在x轴上。我试图使只有一些日期(如90天间隔)写。数据集是从2012-11-07到2022-11-04,所以有很多数据。
密码:

ticker <- "AMAT"

price_data <- returns_long %>% filter(Ticker == ticker, Series == "Close")

price_chart <- ggplot(price_data) +
  geom_line(aes(x = Date, y = Value, group=1), color = "#66CC00") +
  xlab("Date") +
  ylab("Stock Price") +
  labs(
    title = paste0(price_data$Name[1], " (", ticker, ")"),
    subtitle = price_data$Sector[1],
    caption = "Source: Yahoo! Finance"
  )+
  scale_y_continuous(labels = scales::dollar) +
  theme(
    
    plot.background = element_rect(fill = "#17202A"),
    panel.background = element_rect(fill = "#17202A"),
    axis.text.x = element_text(color = "#ffffff", angle = 45, hjust = 1, vjust = 1),
    axis.text.y = element_text(color = "#ffffff"),
    axis.title.x = element_text(color = "#ffffff"),
    axis.title.y = element_text(color = "#ffffff"),
    plot.title = element_text(color = "#ffffff"),
    plot.subtitle = element_text(color = "#ffffff"),
    plot.caption = element_text(color = "#ffffff", face = "italic", size = 6),
    panel.grid.major.x = element_blank(),
    panel.grid.major.y = element_line(color = "#273746"),
    panel.grid.minor.x = element_blank(),
    panel.grid.minor.y = element_blank(),
    legend.position = "none",
    
  )
price_chart

jhdbpxl9

jhdbpxl91#

使用带date_breaks参数的scale_x_date()。例如,

library(ggplot2)

price_chart <- ggplot(price_data) +
  geom_line(aes(x = Date, y = Value, group=1), color = "#66CC00") +
  labs(
    x = "Date",
    y = "Stock Price",
    title = paste0(price_data$Name[1], " (", ticker, ")"),
    subtitle = price_data$Sector[1],
    caption = "Source: Yahoo! Finance"
  ) +
  scale_y_continuous(labels = scales::dollar) +
  scale_x_date(date_breaks = "90 days") +
  theme(
    # as in OP
  )

您可能还想尝试使用date_labelslabels参数。例如,date_labels = "%b %Y"将为您提供"May 2012"而不是"2012-05-20"; labels = ~ lubridate::quarter(.x, type = "year.quarter")会将25美分的硬币给予为"2012.1""2012.2"等。

  • 示例数据:*
set.seed(13)

price_data <- data.frame(
  Date = seq(as.Date("2012-11-07"), as.Date("2022-11-04"), by = 1),
  Value = 50 + cumsum(rnorm(3650)),
  Name = rep("Applied Materials", 3650),
  Sector = rep("Information Technology", 3650)
)

相关问题